security: remove the use of shield in settings

This commit migrates all of the `shield.` settings to `xpack.security.` and makes changes to
use the new Settings infrastructure in core.

As a cleanup, this commit also renames Shield to Security since this class is only in master
and will not affect 2.x.

See elastic/elasticsearch#1441

Original commit: elastic/x-pack-elasticsearch@a5a9798b1b
This commit is contained in:
jaymode 2016-03-22 17:40:45 -04:00
parent b3009c3bdd
commit f888082ce6
126 changed files with 1478 additions and 1072 deletions

View File

@ -7,8 +7,8 @@ dependencies {
integTest {
cluster {
plugin 'x-pack', project(':x-plugins:elasticsearch:x-pack')
setting 'shield.audit.enabled', 'true'
setting 'shield.audit.outputs', 'index'
setting 'xpack.security.audit.enabled', 'true'
setting 'xpack.security.audit.outputs', 'index'
setupCommand 'setupDummyUser',
'bin/x-pack/users', 'useradd', 'test_user', '-p', 'changeme', '-r', 'admin'
waitCondition = { node, ant ->

View File

@ -12,6 +12,7 @@ import org.elasticsearch.cluster.metadata.IndexTemplateMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.audit.index.IndexAuditTrail;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.shield.authc.support.UsernamePasswordToken;
@ -85,7 +86,7 @@ public class IndexAuditIT extends ESIntegTestCase {
@Override
protected Settings externalClusterClientSettings() {
return Settings.builder()
.put("shield.user", USER + ":" + PASS)
.put(Security.USER_SETTING.getKey(), USER + ":" + PASS)
.build();
}

View File

@ -13,6 +13,7 @@ import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.xpack.XPackPlugin;
@ -35,7 +36,7 @@ public class ShieldTransportClientIT extends ESIntegTestCase {
@Override
protected Settings externalClusterClientSettings() {
return Settings.builder()
.put("shield.user", ADMIN_USER_PW)
.put(Security.USER_SETTING.getKey(), ADMIN_USER_PW)
.build();
}
@ -56,7 +57,7 @@ public class ShieldTransportClientIT extends ESIntegTestCase {
public void testThatTransportClientAuthenticationWithTransportClientRole() throws Exception {
Settings settings = Settings.builder()
.put("shield.user", TRANSPORT_USER_PW)
.put(Security.USER_SETTING.getKey(), TRANSPORT_USER_PW)
.build();
try (TransportClient client = transportClient(settings)) {
boolean connected = awaitBusy(() -> {
@ -78,7 +79,7 @@ public class ShieldTransportClientIT extends ESIntegTestCase {
public void testTransportClientWithAdminUser() throws Exception {
final boolean useTransportUser = randomBoolean();
Settings settings = Settings.builder()
.put("shield.user", useTransportUser ? TRANSPORT_USER_PW : ADMIN_USER_PW)
.put(Security.USER_SETTING.getKey(), useTransportUser ? TRANSPORT_USER_PW : ADMIN_USER_PW)
.build();
try (TransportClient client = transportClient(settings)) {
boolean connected = awaitBusy(() -> {

View File

@ -35,11 +35,10 @@ task buildZip(type:Zip, dependsOn: [jar]) {
task integTest(type: org.elasticsearch.gradle.test.RestIntegTestTask, dependsOn: buildZip) {
cluster {
plugin 'x-pack', project(':x-plugins:elasticsearch:x-pack')
// TODO: these should be settings?
setting 'shield.authc.realms.custom.order', '0'
setting 'shield.authc.realms.custom.type', 'custom'
setting 'shield.authc.realms.esusers.order', '1'
setting 'shield.authc.realms.esusers.type', 'file'
setting 'xpack.security.authc.realms.custom.order', '0'
setting 'xpack.security.authc.realms.custom.type', 'custom'
setting 'xpack.security.authc.realms.esusers.order', '1'
setting 'xpack.security.authc.realms.esusers.type', 'file'
setupCommand 'setupDummyUser',
'bin/x-pack/users', 'useradd', 'test_user', '-p', 'changeme', '-r', 'admin'

View File

@ -13,6 +13,7 @@ import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.shield.Shield;
import org.hamcrest.Matcher;
import java.util.Collection;
@ -31,7 +32,7 @@ public class MarvelClusterInfoIT extends ESIntegTestCase {
@Override
protected Settings externalClusterClientSettings() {
return Settings.builder()
.put("shield.user", ADMIN_USER_PW)
.put(Shield.USER_SETTING.getKey(), ADMIN_USER_PW)
.build();
}

View File

@ -15,6 +15,7 @@ import org.elasticsearch.client.support.Headers;
import org.elasticsearch.common.network.NetworkAddress;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.shield.authc.support.UsernamePasswordToken;
import org.elasticsearch.test.rest.ESRestTestCase;
@ -80,7 +81,7 @@ public class WatcherWithShieldIT extends ESRestTestCase {
@Override
protected Settings externalClusterClientSettings() {
return Settings.builder()
.put("shield.user", TEST_ADMIN_USERNAME + ":" + TEST_ADMIN_PASSWORD)
.put(Shield.USER_SETTING.getKey(), TEST_ADMIN_USERNAME + ":" + TEST_ADMIN_PASSWORD)
.build();
}

View File

@ -153,10 +153,10 @@ integTest {
setting 'xpack.monitoring.agent.exporters._http.auth.username', 'monitoring_agent'
setting 'xpack.monitoring.agent.exporters._http.auth.password', 'changeme'
setting 'shield.transport.ssl', 'true'
setting 'shield.http.ssl', 'true'
setting 'shield.ssl.keystore.path', nodeKeystore.name
setting 'shield.ssl.keystore.password', 'keypass'
setting 'xpack.security.transport.ssl.enabled', 'true'
setting 'xpack.security.http.ssl.enabled', 'true'
setting 'xpack.security.ssl.keystore.path', nodeKeystore.name
setting 'xpack.security.ssl.keystore.password', 'keypass'
plugin 'x-pack', project(':x-plugins:elasticsearch:x-pack')

View File

@ -12,6 +12,7 @@ import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.transport.netty.ShieldNettyTransport;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.xpack.XPackPlugin;
@ -58,10 +59,10 @@ public class SmokeTestMonitoringWithShieldIT extends ESIntegTestCase {
@Override
protected Settings externalClusterClientSettings() {
return Settings.builder()
.put("shield.user", USER + ":" + PASS)
.put(ShieldNettyTransport.TRANSPORT_SSL_SETTING, true)
.put("shield.ssl.keystore.path", clientKeyStore)
.put("shield.ssl.keystore.password", KEYSTORE_PASS)
.put(Security.USER_SETTING.getKey(), USER + ":" + PASS)
.put(ShieldNettyTransport.SSL_SETTING.getKey(), true)
.put("xpack.security.ssl.keystore.path", clientKeyStore)
.put("xpack.security.ssl.keystore.password", KEYSTORE_PASS)
.build();
}

View File

@ -9,7 +9,7 @@ integTest {
cluster {
plugin 'x-pack', project(':x-plugins:elasticsearch:x-pack')
setting 'script.inline', 'true'
setting 'xpack.shield.enabled', 'false'
setting 'xpack.security.enabled', 'false'
setting 'xpack.monitoring.enabled', 'false'
}
}

View File

@ -8,7 +8,7 @@ dependencies {
integTest {
cluster {
plugin 'x-pack', project(':x-plugins:elasticsearch:x-pack')
setting 'xpack.shield.enabled', 'false'
setting 'xpack.security.enabled', 'false'
setting 'xpack.monitoring.enabled', 'false'
setting 'http.port', '9400'
}

View File

@ -27,7 +27,7 @@ import org.elasticsearch.script.NativeScriptFactory;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.test.ESSingleNodeTestCase;
import org.elasticsearch.watcher.Watcher;
import org.elasticsearch.xpack.XPackPlugin;
@ -125,7 +125,7 @@ public class GraphTests extends ESSingleNodeTestCase {
public Settings nodeSettings() {
// Disable Shield otherwise authentication failures happen creating indices.
Builder newSettings = Settings.builder();
newSettings.put(XPackPlugin.featureEnabledSetting(Shield.NAME), false);
newSettings.put(XPackPlugin.featureEnabledSetting(Security.NAME), false);
newSettings.put(XPackPlugin.featureEnabledSetting(Marvel.NAME), false);
newSettings.put(XPackPlugin.featureEnabledSetting(Watcher.NAME), false);
return newSettings.build();

View File

@ -26,7 +26,7 @@ import org.elasticsearch.license.plugin.core.LicensesMetaData;
import org.elasticsearch.license.plugin.core.LicensesStatus;
import org.elasticsearch.marvel.Marvel;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.watcher.Watcher;
@ -48,7 +48,7 @@ public abstract class AbstractLicensesIntegrationTestCase extends ESIntegTestCas
@Override
protected Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(XPackPlugin.featureEnabledSetting(Shield.NAME), false)
.put(XPackPlugin.featureEnabledSetting(Security.NAME), false)
.put(XPackPlugin.featureEnabledSetting(Marvel.NAME), false)
.put(XPackPlugin.featureEnabledSetting(Watcher.NAME), false)
.put(XPackPlugin.featureEnabledSetting(Graph.NAME), false)

View File

@ -18,7 +18,7 @@ import org.elasticsearch.marvel.agent.collector.AbstractCollector;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc;
import org.elasticsearch.marvel.license.MarvelLicensee;
import org.elasticsearch.shield.InternalClient;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import java.util.ArrayList;
import java.util.Arrays;
@ -69,7 +69,7 @@ public class IndexRecoveryCollector extends AbstractCollector<IndexRecoveryColle
results.add(indexRecoveryDoc);
}
} catch (IndexNotFoundException e) {
if (Shield.enabled(settings) && IndexNameExpressionResolver.isAllIndices(Arrays.asList(marvelSettings.indices()))) {
if (Security.enabled(settings) && IndexNameExpressionResolver.isAllIndices(Arrays.asList(marvelSettings.indices()))) {
logger.debug("collector [{}] - unable to collect data for missing index [{}]", name(), e.getIndex());
} else {
throw e;

View File

@ -20,7 +20,7 @@ import org.elasticsearch.marvel.agent.collector.AbstractCollector;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc;
import org.elasticsearch.marvel.license.MarvelLicensee;
import org.elasticsearch.shield.InternalClient;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import java.util.ArrayList;
import java.util.Arrays;
@ -83,7 +83,7 @@ public class IndexStatsCollector extends AbstractCollector<IndexStatsCollector>
results.add(indexStatsDoc);
}
} catch (IndexNotFoundException e) {
if (Shield.enabled(settings) && IndexNameExpressionResolver.isAllIndices(Arrays.asList(marvelSettings.indices()))) {
if (Security.enabled(settings) && IndexNameExpressionResolver.isAllIndices(Arrays.asList(marvelSettings.indices()))) {
logger.debug("collector [{}] - unable to collect data for missing index [{}]", name(), e.getIndex());
} else {
throw e;

View File

@ -18,7 +18,7 @@ import org.elasticsearch.marvel.agent.collector.AbstractCollector;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc;
import org.elasticsearch.marvel.license.MarvelLicensee;
import org.elasticsearch.shield.InternalClient;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import java.util.Arrays;
import java.util.Collection;
@ -68,7 +68,7 @@ public class IndicesStatsCollector extends AbstractCollector<IndicesStatsCollect
return Collections.singletonList(indicesStatsDoc);
} catch (IndexNotFoundException e) {
if (Shield.enabled(settings) && IndexNameExpressionResolver.isAllIndices(Arrays.asList(marvelSettings.indices()))) {
if (Security.enabled(settings) && IndexNameExpressionResolver.isAllIndices(Arrays.asList(marvelSettings.indices()))) {
logger.debug("collector [{}] - unable to collect data for missing index [{}]", name(), e.getIndex());
return Collections.emptyList();
}

View File

@ -26,8 +26,10 @@ import org.elasticsearch.marvel.agent.resolver.MonitoringIndexNameResolver;
import org.elasticsearch.marvel.client.MonitoringClient;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.shield.authc.file.FileRealm;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.Hasher;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.shield.authz.store.FileRolesStore;
import org.elasticsearch.shield.crypto.InternalCryptoService;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.TestCluster;
@ -118,11 +120,11 @@ public abstract class MarvelIntegTestCase extends ESIntegTestCase {
return Settings.builder()
.put(super.transportClientSettings())
.put("client.transport.sniff", false)
.put("shield.user", "test:changeme")
.put(Security.USER_SETTING.getKey(), "test:changeme")
.build();
}
return Settings.builder().put(super.transportClientSettings())
.put("shield.enabled", false)
.put("xpack.security.enabled", false)
.build();
}
@ -518,22 +520,22 @@ public abstract class MarvelIntegTestCase extends ESIntegTestCase {
public static void apply(boolean enabled, Settings.Builder builder) {
if (!enabled) {
builder.put("shield.enabled", false);
builder.put("xpack.security.enabled", false);
return;
}
try {
Path folder = createTempDir().resolve("marvel_shield");
Files.createDirectories(folder);
builder.put("shield.enabled", true)
.put("shield.authc.realms.file.type", FileRealm.TYPE)
.put("shield.authc.realms.file.order", 0)
.put("shield.authc.realms.file.files.users", writeFile(folder, "users", USERS))
.put("shield.authc.realms.file.files.users_roles", writeFile(folder, "users_roles", USER_ROLES))
.put("shield.authz.store.files.roles", writeFile(folder, "roles.yml", ROLES))
.put("shield.system_key.file", writeFile(folder, "system_key.yml", systemKey))
.put("shield.authc.sign_user_header", false)
.put("shield.audit.enabled", auditLogsEnabled);
builder.put("xpack.security.enabled", true)
.put("xpack.security.authc.realms.esusers.type", FileRealm.TYPE)
.put("xpack.security.authc.realms.esusers.order", 0)
.put("xpack.security.authc.realms.esusers.files.users", writeFile(folder, "users", USERS))
.put("xpack.security.authc.realms.esusers.files.users_roles", writeFile(folder, "users_roles", USER_ROLES))
.put(FileRolesStore.ROLES_FILE_SETTING.getKey(), writeFile(folder, "roles.yml", ROLES))
.put(InternalCryptoService.FILE_SETTING.getKey(), writeFile(folder, "system_key.yml", systemKey))
.put("xpack.security.authc.sign_user_header", false)
.put("xpack.security.audit.enabled", auditLogsEnabled);
} catch (IOException ex) {
throw new RuntimeException("failed to build settings for shield", ex);
}

View File

@ -16,6 +16,7 @@ import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.util.concurrent.ThreadContext;
@ -42,17 +43,19 @@ import org.elasticsearch.shield.audit.AuditTrailModule;
import org.elasticsearch.shield.audit.index.IndexAuditTrail;
import org.elasticsearch.shield.audit.index.IndexNameResolver;
import org.elasticsearch.shield.audit.logfile.LoggingAuditTrail;
import org.elasticsearch.shield.authc.AnonymousService;
import org.elasticsearch.shield.authc.AuthenticationModule;
import org.elasticsearch.shield.authc.InternalAuthenticationService;
import org.elasticsearch.shield.authc.Realms;
import org.elasticsearch.shield.authc.esnative.NativeUsersStore;
import org.elasticsearch.shield.authc.ldap.support.SessionFactory;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.shield.authc.support.UsernamePasswordToken;
import org.elasticsearch.shield.authz.AuthorizationModule;
import org.elasticsearch.shield.authz.accesscontrol.OptOutQueryCache;
import org.elasticsearch.shield.authz.accesscontrol.ShieldIndexSearcherWrapper;
import org.elasticsearch.shield.authz.privilege.ClusterPrivilege;
import org.elasticsearch.shield.authz.privilege.IndexPrivilege;
import org.elasticsearch.shield.authz.store.FileRolesStore;
import org.elasticsearch.shield.authz.store.NativeRolesStore;
import org.elasticsearch.shield.crypto.CryptoModule;
import org.elasticsearch.shield.crypto.InternalCryptoService;
import org.elasticsearch.shield.license.LicenseModule;
@ -70,6 +73,8 @@ import org.elasticsearch.shield.rest.action.user.RestPutUserAction;
import org.elasticsearch.shield.rest.action.user.RestDeleteUserAction;
import org.elasticsearch.shield.rest.action.user.RestGetUsersAction;
import org.elasticsearch.shield.ssl.SSLModule;
import org.elasticsearch.shield.ssl.SSLSettings;
import org.elasticsearch.shield.support.OptionalStringSetting;
import org.elasticsearch.shield.transport.ShieldClientTransportService;
import org.elasticsearch.shield.transport.ShieldServerTransportService;
import org.elasticsearch.shield.transport.ShieldTransportModule;
@ -86,25 +91,27 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
/**
*
*/
public class Shield {
public class Security {
private static final ESLogger logger = Loggers.getLogger(XPackPlugin.class);
public static final String NAME = "shield";
public static final String DLS_FLS_FEATURE = "shield.dls_fls";
public static final String NAME = "security";
public static final String DLS_FLS_FEATURE = "security.dls_fls";
public static final String OPT_OUT_QUERY_CACHE = "opt_out_cache";
public static final Setting<Optional<String>> USER_SETTING = OptionalStringSetting.create(setting("user"), Property.NodeScope);
private final Settings settings;
private final boolean enabled;
private final boolean transportClientMode;
private ShieldLicenseState shieldLicenseState;
public Shield(Settings settings) {
public Security(Settings settings) {
this.settings = settings;
this.transportClientMode = XPackPlugin.transportClientMode(settings);
this.enabled = XPackPlugin.featureEnabled(settings, NAME, true);
@ -166,57 +173,69 @@ public class Shield {
}
Settings.Builder settingsBuilder = Settings.settingsBuilder();
settingsBuilder.put(NetworkModule.TRANSPORT_TYPE_KEY, Shield.NAME);
settingsBuilder.put(NetworkModule.TRANSPORT_SERVICE_TYPE_KEY, Shield.NAME);
settingsBuilder.put(NetworkModule.HTTP_TYPE_SETTING.getKey(), Shield.NAME);
settingsBuilder.put(NetworkModule.TRANSPORT_TYPE_KEY, Security.NAME);
settingsBuilder.put(NetworkModule.TRANSPORT_SERVICE_TYPE_KEY, Security.NAME);
settingsBuilder.put(NetworkModule.HTTP_TYPE_SETTING.getKey(), Security.NAME);
addUserSettings(settingsBuilder);
addTribeSettings(settingsBuilder);
return settingsBuilder.build();
}
public void onModule(SettingsModule settingsModule) {
//TODO shouldn't we register these settings only if shield is enabled and we're not in a client mode?
settingsModule.registerSetting(IPFilter.IP_FILTER_ENABLED_SETTING);
settingsModule.registerSetting(IPFilter.IP_FILTER_ENABLED_HTTP_SETTING);
settingsModule.registerSetting(IPFilter.HTTP_FILTER_ALLOW_SETTING);
settingsModule.registerSetting(IPFilter.HTTP_FILTER_DENY_SETTING);
settingsModule.registerSetting(IPFilter.TRANSPORT_FILTER_ALLOW_SETTING);
settingsModule.registerSetting(IPFilter.TRANSPORT_FILTER_DENY_SETTING);
// always register for both client and node modes
XPackPlugin.registerFeatureEnabledSettings(settingsModule, NAME, true);
XPackPlugin.registerFeatureEnabledSettings(settingsModule, DLS_FLS_FEATURE, true);
settingsModule.registerSetting(Setting.groupSetting("shield.audit.", Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.listSetting("shield.hide_settings", Collections.emptyList(), Function.identity(),
Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.groupSetting("shield.ssl.", Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.groupSetting("shield.authc.", Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.simpleString("shield.authz.store.files.roles", Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.simpleString("shield.system_key.file", Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.boolSetting(ShieldNettyHttpServerTransport.HTTP_SSL_SETTING,
ShieldNettyHttpServerTransport.HTTP_SSL_DEFAULT, Setting.Property.NodeScope));
// FIXME need to register a real setting with the defaults here
settingsModule.registerSetting(Setting.simpleString(ShieldNettyHttpServerTransport.HTTP_CLIENT_AUTH_SETTING,
Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.boolSetting(ShieldNettyTransport.TRANSPORT_SSL_SETTING,
ShieldNettyTransport.TRANSPORT_SSL_DEFAULT, Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.simpleString(ShieldNettyTransport.TRANSPORT_CLIENT_AUTH_SETTING,
Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.simpleString("shield.user", Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.simpleString("shield.encryption_key.algorithm", Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.simpleString("shield.encryption.algorithm", Setting.Property.NodeScope));
settingsModule.registerSetting(USER_SETTING);
String[] asArray = settings.getAsArray("shield.hide_settings");
// SSL settings
SSLSettings.registerSettings(settingsModule);
// transport settings
ShieldNettyTransport.registerSettings(settingsModule);
if (transportClientMode) {
return;
}
// The following just apply in node mode
XPackPlugin.registerFeatureEnabledSettings(settingsModule, DLS_FLS_FEATURE, true);
// IP Filter settings
IPFilter.registerSettings(settingsModule);
// audit settings
AuditTrailModule.registerSettings(settingsModule);
// authentication settings
FileRolesStore.registerSettings(settingsModule);
AnonymousService.registerSettings(settingsModule);
Realms.registerSettings(settingsModule);
NativeUsersStore.registerSettings(settingsModule);
NativeRolesStore.registerSettings(settingsModule);
InternalAuthenticationService.registerSettings(settingsModule);
// HTTP settings
ShieldNettyHttpServerTransport.registerSettings(settingsModule);
// encryption settings
InternalCryptoService.registerSettings(settingsModule);
// hide settings
settingsModule.registerSetting(Setting.listSetting(setting("hide_settings"), Collections.emptyList(), Function.identity(),
Property.NodeScope, Property.Filtered));
String[] asArray = settings.getAsArray(setting("hide_settings"));
for (String pattern : asArray) {
settingsModule.registerSettingsFilter(pattern);
}
settingsModule.registerSettingsFilter("shield.hide_settings");
settingsModule.registerSettingsFilter("shield.ssl.*");
settingsModule.registerSettingsFilter("shield.authc.realms.*.bind_dn");
settingsModule.registerSettingsFilter("shield.authc.realms.*.bind_password");
settingsModule.registerSettingsFilter("shield.authc.realms.*." + SessionFactory.HOSTNAME_VERIFICATION_SETTING);
settingsModule.registerSettingsFilter("shield.authc.realms.*.truststore.password");
settingsModule.registerSettingsFilter("shield.authc.realms.*.truststore.path");
settingsModule.registerSettingsFilter("shield.authc.realms.*.truststore.algorithm");
settingsModule.registerSettingsFilter("transport.profiles.*.shield.*");
settingsModule.registerSettingsFilter(setting("authc.realms.*.bind_dn"));
settingsModule.registerSettingsFilter(setting("authc.realms.*.bind_password"));
settingsModule.registerSettingsFilter(setting("authc.realms.*." + SessionFactory.HOSTNAME_VERIFICATION_SETTING));
settingsModule.registerSettingsFilter(setting("authc.realms.*.truststore.password"));
settingsModule.registerSettingsFilter(setting("authc.realms.*.truststore.path"));
settingsModule.registerSettingsFilter(setting("authc.realms.*.truststore.algorithm"));
// hide settings where we don't define them - they are part of a group...
settingsModule.registerSettingsFilter("transport.profiles.*." + setting("*"));
}
public void onIndexModule(IndexModule module) {
@ -232,12 +251,12 @@ public class Shield {
shieldLicenseState));
}
if (transportClientMode == false) {
module.registerQueryCache(Shield.OPT_OUT_QUERY_CACHE, OptOutQueryCache::new);
module.registerQueryCache(Security.OPT_OUT_QUERY_CACHE, OptOutQueryCache::new);
/* We need to forcefully overwrite the query cache implementation to use Shield's opt out query cache implementation.
* This impl. disabled the query cache if field level security is used for a particular request. If we wouldn't do
* forcefully overwrite the query cache implementation then we leave the system vulnerable to leakages of data to
* unauthorized users. */
module.forceQueryCacheType(Shield.OPT_OUT_QUERY_CACHE);
module.forceQueryCacheType(Security.OPT_OUT_QUERY_CACHE);
}
}
@ -265,8 +284,8 @@ public class Shield {
if (transportClientMode) {
if (enabled) {
module.registerTransport(Shield.NAME, ShieldNettyTransport.class);
module.registerTransportService(Shield.NAME, ShieldClientTransportService.class);
module.registerTransport(Security.NAME, ShieldNettyTransport.class);
module.registerTransportService(Security.NAME, ShieldClientTransportService.class);
}
return;
}
@ -275,8 +294,8 @@ public class Shield {
module.registerRestHandler(RestShieldInfoAction.class);
if (enabled) {
module.registerTransport(Shield.NAME, ShieldNettyTransport.class);
module.registerTransportService(Shield.NAME, ShieldServerTransportService.class);
module.registerTransport(Security.NAME, ShieldNettyTransport.class);
module.registerTransportService(Security.NAME, ShieldServerTransportService.class);
module.registerRestHandler(RestAuthenticateAction.class);
module.registerRestHandler(RestClearRealmCacheAction.class);
module.registerRestHandler(RestClearRolesCacheAction.class);
@ -286,7 +305,7 @@ public class Shield {
module.registerRestHandler(RestGetRolesAction.class);
module.registerRestHandler(RestPutRoleAction.class);
module.registerRestHandler(RestDeleteRoleAction.class);
module.registerHttpTransport(Shield.NAME, ShieldNettyHttpServerTransport.class);
module.registerHttpTransport(Security.NAME, ShieldNettyHttpServerTransport.class);
}
}
@ -295,18 +314,18 @@ public class Shield {
if (settings.get(authHeaderSettingName) != null) {
return;
}
String userSetting = settings.get("shield.user");
if (userSetting == null) {
return;
}
int i = userSetting.indexOf(":");
Optional<String> userOptional = USER_SETTING.get(settings);
userOptional.ifPresent(userSetting -> {
final int i = userSetting.indexOf(":");
if (i < 0 || i == userSetting.length() - 1) {
throw new IllegalArgumentException("invalid [shield.user] setting. must be in the form of \"<username>:<password>\"");
throw new IllegalArgumentException("invalid [" + USER_SETTING.getKey() + "] setting. must be in the form of " +
"\"<username>:<password>\"");
}
String username = userSetting.substring(0, i);
String password = userSetting.substring(i + 1);
settingsBuilder.put(authHeaderSettingName, UsernamePasswordToken.basicAuthHeaderValue(username, new SecuredString(password
.toCharArray())));
});
}
/**
@ -357,7 +376,7 @@ public class Shield {
// we passed all the checks now we need to copy in all of the shield settings
for (Map.Entry<String, String> entry : settingsMap.entrySet()) {
String key = entry.getKey();
if (key.startsWith("shield.")) {
if (key.startsWith("xpack.security.")) {
settingsBuilder.put(tribePrefix + key, entry.getValue());
}
}
@ -372,6 +391,23 @@ public class Shield {
return XPackPlugin.featureEnabled(settings, DLS_FLS_FEATURE, true);
}
public static String enabledSetting() {
return XPackPlugin.featureEnabledSetting(NAME);
}
public static String settingPrefix() {
return XPackPlugin.featureSettingPrefix(NAME) + ".";
}
public static String setting(String setting) {
assert setting != null && setting.startsWith(".") == false;
return settingPrefix() + setting;
}
public static String featureEnabledSetting(String feature) {
assert feature != null && feature.startsWith(".") == false;
return XPackPlugin.featureEnabledSetting("security." + feature);
}
static void validateAutoCreateIndex(Settings settings) {
String value = settings.get("action.auto_create_index");

View File

@ -19,7 +19,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.license.plugin.core.LicenseUtils;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.SystemUser;
import org.elasticsearch.shield.User;
import org.elasticsearch.shield.action.interceptor.RequestInterceptor;
@ -88,7 +88,7 @@ public class ShieldActionFilter extends AbstractComponent implements ActionFilte
logger.error("blocking [{}] operation due to expired license. Cluster health, cluster stats and indices stats \n" +
"operations are blocked on shield license expiration. All data operations (read and write) continue to work. \n" +
"If you have a new license, please update it. Otherwise, please reach out to your support contact.", action);
throw LicenseUtils.newComplianceException(Shield.NAME);
throw LicenseUtils.newComplianceException(Security.NAME);
}
// only restore the context if it is not empty. This is needed because sometimes a response is sent to the user

View File

@ -7,24 +7,40 @@ package org.elasticsearch.shield.audit;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.inject.multibindings.Multibinder;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.shield.audit.index.IndexAuditTrail;
import org.elasticsearch.shield.audit.logfile.LoggingAuditTrail;
import org.elasticsearch.shield.support.AbstractShieldModule;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import static org.elasticsearch.shield.Security.featureEnabledSetting;
import static org.elasticsearch.shield.Security.setting;
/**
*
*/
public class AuditTrailModule extends AbstractShieldModule.Node {
public static final Setting<Boolean> ENABLED_SETTING =
Setting.boolSetting(featureEnabledSetting("audit"), false, Property.NodeScope);
public static final Setting<List<String>> OUTPUTS_SETTING =
Setting.listSetting(setting("audit.outputs"),
s -> s.getAsMap().containsKey(setting("audit.outputs")) ?
Collections.emptyList() : Collections.singletonList(LoggingAuditTrail.NAME),
Function.identity(), Property.NodeScope);
private final boolean enabled;
public AuditTrailModule(Settings settings) {
super(settings);
enabled = auditingEnabled(settings);
enabled = ENABLED_SETTING.get(settings);
}
@Override
@ -33,8 +49,8 @@ public class AuditTrailModule extends AbstractShieldModule.Node {
bind(AuditTrail.class).toInstance(AuditTrail.NOOP);
return;
}
String[] outputs = settings.getAsArray("shield.audit.outputs", new String[] { LoggingAuditTrail.NAME });
if (outputs.length == 0) {
List<String> outputs = OUTPUTS_SETTING.get(settings);
if (outputs.isEmpty()) {
bind(AuditTrail.class).toInstance(AuditTrail.NOOP);
return;
}
@ -59,12 +75,12 @@ public class AuditTrailModule extends AbstractShieldModule.Node {
}
public static boolean auditingEnabled(Settings settings) {
return settings.getAsBoolean("shield.audit.enabled", false);
return ENABLED_SETTING.get(settings);
}
public static boolean indexAuditLoggingEnabled(Settings settings) {
if (auditingEnabled(settings)) {
String[] outputs = settings.getAsArray("shield.audit.outputs");
List<String> outputs = OUTPUTS_SETTING.get(settings);
for (String output : outputs) {
if (output.equals(IndexAuditTrail.NAME)) {
return true;
@ -76,7 +92,7 @@ public class AuditTrailModule extends AbstractShieldModule.Node {
public static boolean fileAuditLoggingEnabled(Settings settings) {
if (auditingEnabled(settings)) {
String[] outputs = settings.getAsArray("shield.audit.outputs", new String[] { LoggingAuditTrail.NAME });
List<String> outputs = OUTPUTS_SETTING.get(settings);
for (String output : outputs) {
if (output.equals(LoggingAuditTrail.NAME)) {
return true;
@ -85,4 +101,11 @@ public class AuditTrailModule extends AbstractShieldModule.Node {
}
return false;
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(ENABLED_SETTING);
settingsModule.registerSetting(OUTPUTS_SETTING);
LoggingAuditTrail.registerSettings(settingsModule);
IndexAuditTrail.registerSettings(settingsModule);
}
}

View File

@ -7,6 +7,7 @@ package org.elasticsearch.shield.audit.index;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
public enum IndexAuditLevel {
@ -22,7 +23,7 @@ public enum IndexAuditLevel {
RUN_AS_GRANTED,
RUN_AS_DENIED;
static EnumSet<IndexAuditLevel> parse(String[] levels) {
static EnumSet<IndexAuditLevel> parse(List<String> levels) {
EnumSet<IndexAuditLevel> enumSet = EnumSet.noneOf(IndexAuditLevel.class);
for (String level : levels) {
String lowerCaseLevel = level.trim().toLowerCase(Locale.ROOT);
@ -67,7 +68,7 @@ public enum IndexAuditLevel {
return enumSet;
}
public static EnumSet<IndexAuditLevel> parse(String[] includeLevels, String[] excludeLevels) {
public static EnumSet<IndexAuditLevel> parse(List<String> includeLevels, List<String> excludeLevels) {
EnumSet<IndexAuditLevel> included = parse(includeLevels);
EnumSet<IndexAuditLevel> excluded = parse(excludeLevels);
included.removeAll(excluded);

View File

@ -24,14 +24,16 @@ import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.Provider;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.network.NetworkAddress;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
@ -49,7 +51,6 @@ import org.elasticsearch.shield.SystemUser;
import org.elasticsearch.shield.User;
import org.elasticsearch.shield.XPackUser;
import org.elasticsearch.shield.audit.AuditTrail;
import org.elasticsearch.shield.authc.AuthenticationService;
import org.elasticsearch.shield.authc.AuthenticationToken;
import org.elasticsearch.shield.authz.privilege.SystemPrivilege;
import org.elasticsearch.shield.rest.RemoteHostHeader;
@ -70,6 +71,7 @@ import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
@ -78,6 +80,7 @@ import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import static org.elasticsearch.shield.audit.AuditUtil.indices;
import static org.elasticsearch.shield.audit.AuditUtil.restRequestContent;
@ -93,6 +96,7 @@ import static org.elasticsearch.shield.audit.index.IndexAuditLevel.SYSTEM_ACCESS
import static org.elasticsearch.shield.audit.index.IndexAuditLevel.TAMPERED_REQUEST;
import static org.elasticsearch.shield.audit.index.IndexAuditLevel.parse;
import static org.elasticsearch.shield.audit.index.IndexNameResolver.resolve;
import static org.elasticsearch.shield.Security.setting;
/**
* Audit trail implementation that writes events into an index.
@ -107,12 +111,15 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail, Cl
public static final String NAME = "index";
public static final String INDEX_NAME_PREFIX = ".shield_audit_log";
public static final String DOC_TYPE = "event";
public static final String ROLLOVER_SETTING = "shield.audit.index.rollover";
public static final String QUEUE_SIZE_SETTING = "shield.audit.index.queue_max_size";
public static final Setting<IndexNameResolver.Rollover> ROLLOVER_SETTING =
new Setting<>(setting("audit.index.rollover"), (s) -> DEFAULT_ROLLOVER.name(),
s -> IndexNameResolver.Rollover.valueOf(s.toUpperCase(Locale.ENGLISH)), Property.NodeScope);
public static final Setting<Integer> QUEUE_SIZE_SETTING =
Setting.intSetting(setting("audit.index.queue_max_size"), DEFAULT_MAX_QUEUE_SIZE, 1, Property.NodeScope);
public static final String INDEX_TEMPLATE_NAME = "shield_audit_log";
public static final String DEFAULT_CLIENT_NAME = "shield-audit-client";
static final String[] DEFAULT_EVENT_INCLUDES = new String[]{
static final List<String> DEFAULT_EVENT_INCLUDES = Arrays.asList(
ACCESS_DENIED.toString(),
ACCESS_GRANTED.toString(),
ANONYMOUS_ACCESS_DENIED.toString(),
@ -122,14 +129,29 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail, Cl
TAMPERED_REQUEST.toString(),
RUN_AS_DENIED.toString(),
RUN_AS_GRANTED.toString()
};
);
private static final String FORBIDDEN_INDEX_SETTING = "index.mapper.dynamic";
public static final Setting<Settings> INDEX_SETTINGS =
Setting.groupSetting(setting("audit.index.settings.index."), Property.NodeScope);
public static final Setting<List<String>> INCLUDE_EVENT_SETTINGS =
Setting.listSetting(setting("audit.index.events.include"), DEFAULT_EVENT_INCLUDES, Function.identity(),
Property.NodeScope);
public static final Setting<List<String>> EXCLUDE_EVENT_SETTINGS =
Setting.listSetting(setting("audit.index.events.exclude"), Collections.emptyList(),
Function.identity(), Property.NodeScope);
public static final Setting<Settings> REMOTE_CLIENT_SETTINGS =
Setting.groupSetting(setting("audit.index.client."), Property.NodeScope);
public static final Setting<Integer> BULK_SIZE_SETTING =
Setting.intSetting(setting("audit.index.bulk_size"), DEFAULT_BULK_SIZE, 1, MAX_BULK_SIZE, Property.NodeScope);
public static final Setting<TimeValue> FLUSH_TIMEOUT_SETTING =
Setting.timeSetting(setting("audit.index.flush_interval"), DEFAULT_FLUSH_INTERVAL,
TimeValue.timeValueMillis(1L), Property.NodeScope);
private final AtomicReference<State> state = new AtomicReference<>(State.INITIALIZED);
private final String nodeName;
private final Provider<InternalClient> clientProvider;
private final AuthenticationService authenticationService;
private final LinkedBlockingQueue<Message> eventQueue;
private final QueueConsumer queueConsumer;
private final Transport transport;
@ -151,10 +173,9 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail, Cl
}
@Inject
public IndexAuditTrail(Settings settings, AuthenticationService authenticationService, Transport transport,
public IndexAuditTrail(Settings settings, Transport transport,
Provider<InternalClient> clientProvider, ThreadPool threadPool, ClusterService clusterService) {
super(settings);
this.authenticationService = authenticationService;
this.clientProvider = clientProvider;
this.transport = transport;
this.threadPool = threadPool;
@ -162,35 +183,23 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail, Cl
this.nodeName = settings.get("name");
this.queueConsumer = new QueueConsumer(EsExecutors.threadName(settings, "audit-queue-consumer"));
int maxQueueSize = settings.getAsInt(QUEUE_SIZE_SETTING, DEFAULT_MAX_QUEUE_SIZE);
if (maxQueueSize <= 0) {
logger.warn("invalid value [{}] for setting [{}]. using default value [{}]", maxQueueSize, QUEUE_SIZE_SETTING,
DEFAULT_MAX_QUEUE_SIZE);
maxQueueSize = DEFAULT_MAX_QUEUE_SIZE;
}
int maxQueueSize = QUEUE_SIZE_SETTING.get(settings);
this.eventQueue = new LinkedBlockingQueue<>(maxQueueSize);
// we have to initialize this here since we use rollover in determining if we can start...
try {
rollover = IndexNameResolver.Rollover.valueOf(
settings.get(ROLLOVER_SETTING, DEFAULT_ROLLOVER.name()).toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException e) {
logger.warn("invalid value for setting [shield.audit.index.rollover]; falling back to default [{}]",
DEFAULT_ROLLOVER.name());
rollover = DEFAULT_ROLLOVER;
}
rollover = ROLLOVER_SETTING.get(settings);
// we have to initialize the events here since we can receive events before starting...
String[] includedEvents = settings.getAsArray("shield.audit.index.events.include", DEFAULT_EVENT_INCLUDES);
String[] excludedEvents = settings.getAsArray("shield.audit.index.events.exclude");
List<String> includedEvents = INCLUDE_EVENT_SETTINGS.get(settings);
List<String> excludedEvents = EXCLUDE_EVENT_SETTINGS.get(settings);
try {
events = parse(includedEvents, excludedEvents);
} catch (IllegalArgumentException e) {
logger.warn("invalid event type specified, using default for audit index output. include events [{}], exclude events [{}]",
e, includedEvents, excludedEvents);
events = parse(DEFAULT_EVENT_INCLUDES, Strings.EMPTY_ARRAY);
events = parse(DEFAULT_EVENT_INCLUDES, Collections.emptyList());
}
this.indexToRemoteCluster = settings.getByPrefix("shield.audit.index.client.").names().size() > 0;
this.indexToRemoteCluster = REMOTE_CLIENT_SETTINGS.get(settings).names().size() > 0;
}
@ -684,16 +693,16 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail, Cl
// in the absence of client settings for remote indexing, fall back to the client that was passed in.
this.client = clientProvider.get();
} else {
Settings clientSettings = settings.getByPrefix("shield.audit.index.client.");
Settings clientSettings = REMOTE_CLIENT_SETTINGS.get(settings);
String[] hosts = clientSettings.getAsArray("hosts");
if (hosts.length == 0) {
throw new ElasticsearchException("missing required setting " +
"[shield.audit.index.client.hosts] for remote audit log indexing");
"[" + REMOTE_CLIENT_SETTINGS.getKey() + ".hosts] for remote audit log indexing");
}
if (clientSettings.get("cluster.name", "").isEmpty()) {
throw new ElasticsearchException("missing required setting " +
"[shield.audit.index.client.cluster.name] for remote audit log indexing");
"[" + REMOTE_CLIENT_SETTINGS.getKey() + ".cluster.name] for remote audit log indexing");
}
List<Tuple<String, Integer>> hostPortPairs = new ArrayList<>();
@ -701,13 +710,14 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail, Cl
for (String host : hosts) {
List<String> hostPort = Arrays.asList(host.trim().split(":"));
if (hostPort.size() != 1 && hostPort.size() != 2) {
logger.warn("invalid host:port specified: [{}] for setting [shield.audit.index.client.hosts]", host);
logger.warn("invalid host:port specified: [{}] for setting [" + REMOTE_CLIENT_SETTINGS.getKey() + ".hosts]", host);
}
hostPortPairs.add(new Tuple<>(hostPort.get(0), hostPort.size() == 2 ? Integer.valueOf(hostPort.get(1)) : 9300));
}
if (hostPortPairs.size() == 0) {
throw new ElasticsearchException("no valid host:port pairs specified for setting [shield.audit.index.client.hosts]");
throw new ElasticsearchException("no valid host:port pairs specified for setting ["
+ REMOTE_CLIENT_SETTINGS.getKey() + ".hosts]");
}
final Settings theClientSetting = clientSettings.filter((s) -> s.startsWith("hosts") == false); // hosts is not a valid setting
final TransportClient transportClient = TransportClient.builder()
@ -732,7 +742,7 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail, Cl
Settings customAuditIndexSettings(Settings nodeSettings) {
Settings newSettings = Settings.builder()
.put(nodeSettings.getAsSettings("shield.audit.index.settings.index"))
.put(INDEX_SETTINGS.get(nodeSettings))
.build();
if (newSettings.names().isEmpty()) {
return Settings.EMPTY;
@ -801,11 +811,8 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail, Cl
private void initializeBulkProcessor() {
int bulkSize = Math.min(settings.getAsInt("shield.audit.index.bulk_size", DEFAULT_BULK_SIZE), MAX_BULK_SIZE);
bulkSize = (bulkSize < 1) ? DEFAULT_BULK_SIZE : bulkSize;
TimeValue interval = settings.getAsTime("shield.audit.index.flush_interval", DEFAULT_FLUSH_INTERVAL);
interval = (interval.millis() < 1) ? DEFAULT_FLUSH_INTERVAL : interval;
final int bulkSize = BULK_SIZE_SETTING.get(settings);
final TimeValue interval = FLUSH_TIMEOUT_SETTING.get(settings);
bulkProcessor = BulkProcessor.builder(client, new BulkProcessor.Listener() {
@Override
@ -866,6 +873,17 @@ public class IndexAuditTrail extends AbstractComponent implements AuditTrail, Cl
}
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(INDEX_SETTINGS);
settingsModule.registerSetting(EXCLUDE_EVENT_SETTINGS);
settingsModule.registerSetting(INCLUDE_EVENT_SETTINGS);
settingsModule.registerSetting(ROLLOVER_SETTING);
settingsModule.registerSetting(BULK_SIZE_SETTING);
settingsModule.registerSetting(FLUSH_TIMEOUT_SETTING);
settingsModule.registerSetting(QUEUE_SIZE_SETTING);
settingsModule.registerSetting(REMOTE_CLIENT_SETTINGS);
}
private class QueueConsumer extends Thread {
volatile boolean running = true;

View File

@ -12,7 +12,10 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.network.NetworkAddress;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.util.concurrent.ThreadContext;
@ -36,6 +39,7 @@ import java.net.SocketAddress;
import static org.elasticsearch.common.Strings.arrayToCommaDelimitedString;
import static org.elasticsearch.shield.audit.AuditUtil.indices;
import static org.elasticsearch.shield.audit.AuditUtil.restRequestContent;
import static org.elasticsearch.shield.Security.setting;
/**
*
@ -43,6 +47,12 @@ import static org.elasticsearch.shield.audit.AuditUtil.restRequestContent;
public class LoggingAuditTrail extends AbstractLifecycleComponent<LoggingAuditTrail> implements AuditTrail {
public static final String NAME = "logfile";
public static final Setting<Boolean> HOST_ADDRESS_SETTING =
Setting.boolSetting(setting("audit.logfile.prefix.emit_node_host_address"), false, Property.NodeScope);
public static final Setting<Boolean> HOST_NAME_SETTING =
Setting.boolSetting(setting("audit.logfile.prefix.emit_node_host_name"), false, Property.NodeScope);
public static final Setting<Boolean> NODE_NAME_SETTING =
Setting.boolSetting(setting("audit.logfile.prefix.emit_node_name"), true, Property.NodeScope);
private final ESLogger logger;
private final Transport transport;
@ -409,19 +419,19 @@ public class LoggingAuditTrail extends AbstractLifecycleComponent<LoggingAuditTr
static String resolvePrefix(Settings settings, Transport transport) {
StringBuilder builder = new StringBuilder();
if (settings.getAsBoolean("shield.audit.logfile.prefix.emit_node_host_address", false)) {
if (HOST_ADDRESS_SETTING.get(settings)) {
String address = transport.boundAddress().publishAddress().getAddress();
if (address != null) {
builder.append("[").append(address).append("] ");
}
}
if (settings.getAsBoolean("shield.audit.logfile.prefix.emit_node_host_name", false)) {
if (HOST_NAME_SETTING.get(settings)) {
String hostName = transport.boundAddress().publishAddress().getHost();
if (hostName != null) {
builder.append("[").append(hostName).append("] ");
}
}
if (settings.getAsBoolean("shield.audit.logfile.prefix.emit_node_name", true)) {
if (NODE_NAME_SETTING.get(settings)) {
String name = settings.get("name");
if (name != null) {
builder.append("[").append(name).append("] ");
@ -442,4 +452,10 @@ public class LoggingAuditTrail extends AbstractLifecycleComponent<LoggingAuditTr
}
return builder.append(user.principal()).append("]").toString();
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(HOST_ADDRESS_SETTING);
settingsModule.registerSetting(HOST_NAME_SETTING);
settingsModule.registerSetting(NODE_NAME_SETTING);
}
}

View File

@ -6,15 +6,28 @@
package org.elasticsearch.shield.authc;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.shield.User;
import java.util.Collections;
import java.util.List;
import static org.elasticsearch.shield.Security.setting;
public class AnonymousService {
public static final String SETTING_AUTHORIZATION_EXCEPTION_ENABLED = "shield.authc.anonymous.authz_exception";
static final String ANONYMOUS_USERNAME = "_es_anonymous_user";
public static final Setting<Boolean> SETTING_AUTHORIZATION_EXCEPTION_ENABLED =
Setting.boolSetting(setting("authc.anonymous.authz_exception"), true, Property.NodeScope);
public static final Setting<List<String>> ROLES_SETTING =
Setting.listSetting(setting("authc.anonymous.roles"), Collections.emptyList(), s -> s, Property.NodeScope);
public static final Setting<String> USERNAME_SETTING =
new Setting<>(setting("authc.anonymous.username"), ANONYMOUS_USERNAME, s -> s, Property.NodeScope);
@Nullable
private final User anonymousUser;
@ -23,7 +36,7 @@ public class AnonymousService {
@Inject
public AnonymousService(Settings settings) {
anonymousUser = resolveAnonymousUser(settings);
authzExceptionEnabled = settings.getAsBoolean(SETTING_AUTHORIZATION_EXCEPTION_ENABLED, true);
authzExceptionEnabled = SETTING_AUTHORIZATION_EXCEPTION_ENABLED.get(settings);
}
public boolean enabled() {
@ -46,11 +59,17 @@ public class AnonymousService {
}
static User resolveAnonymousUser(Settings settings) {
String[] roles = settings.getAsArray("shield.authc.anonymous.roles", null);
if (roles == null) {
List<String> roles = ROLES_SETTING.get(settings);
if (roles.isEmpty()) {
return null;
}
String username = settings.get("shield.authc.anonymous.username", ANONYMOUS_USERNAME);
return new User(username, roles);
String username = USERNAME_SETTING.get(settings);
return new User(username, roles.toArray(Strings.EMPTY_ARRAY));
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(ROLES_SETTING);
settingsModule.registerSetting(USERNAME_SETTING);
settingsModule.registerSetting(SETTING_AUTHORIZATION_EXCEPTION_ENABLED);
}
}

View File

@ -9,6 +9,7 @@ import org.elasticsearch.common.inject.multibindings.MapBinder;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.shield.authc.activedirectory.ActiveDirectoryRealm;
import org.elasticsearch.shield.authc.esnative.NativeRealm;
import org.elasticsearch.shield.authc.esnative.NativeUsersStore;
import org.elasticsearch.shield.authc.file.FileRealm;
import org.elasticsearch.shield.authc.ldap.LdapRealm;
import org.elasticsearch.shield.authc.pki.PkiRealm;
@ -58,6 +59,7 @@ public class AuthenticationModule extends AbstractShieldModule.Node {
bind(AuthenticationFailureHandler.class).to(authcFailureHandler).asEagerSingleton();
}
bind(AuthenticationService.class).to(InternalAuthenticationService.class).asEagerSingleton();
bind(NativeUsersStore.class).asEagerSingleton();
}
/**

View File

@ -14,7 +14,10 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.shield.User;
@ -25,6 +28,7 @@ import org.elasticsearch.transport.TransportMessage;
import java.io.IOException;
import static org.elasticsearch.shield.Security.setting;
import static org.elasticsearch.shield.support.Exceptions.authenticationError;
/**
@ -34,8 +38,10 @@ import static org.elasticsearch.shield.support.Exceptions.authenticationError;
*/
public class InternalAuthenticationService extends AbstractComponent implements AuthenticationService {
public static final String SETTING_SIGN_USER_HEADER = "shield.authc.sign_user_header";
public static final String SETTING_RUN_AS_ENABLED = "shield.authc.run_as.enabled";
public static final Setting<Boolean> SIGN_USER_HEADER =
Setting.boolSetting(setting("authc.sign_user_header"), true, Property.NodeScope);
public static final Setting<Boolean> RUN_AS_ENABLED =
Setting.boolSetting(setting("authc.run_as.enabled"), true, Property.NodeScope);
public static final String RUN_AS_USER_HEADER = "es-shield-runas-user";
static final String TOKEN_KEY = "_shield_token";
@ -61,8 +67,8 @@ public class InternalAuthenticationService extends AbstractComponent implements
this.anonymousService = anonymousService;
this.failureHandler = failureHandler;
this.threadContext = threadPool.getThreadContext();
this.signUserHeader = settings.getAsBoolean(SETTING_SIGN_USER_HEADER, true);
this.runAsEnabled = settings.getAsBoolean(SETTING_RUN_AS_ENABLED, true);
this.signUserHeader = SIGN_USER_HEADER.get(settings);
this.runAsEnabled = RUN_AS_ENABLED.get(settings);
}
@Override
@ -430,4 +436,9 @@ public class InternalAuthenticationService extends AbstractComponent implements
}
return null;
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(SIGN_USER_HEADER);
settingsModule.registerSetting(RUN_AS_ENABLED);
}
}

View File

@ -8,7 +8,10 @@ package org.elasticsearch.shield.authc;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.authc.esnative.NativeRealm;
import org.elasticsearch.shield.authc.file.FileRealm;
@ -22,11 +25,15 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.elasticsearch.shield.Security.setting;
/**
* Serves as a realms registry (also responsible for ordering the realms appropriately)
*/
public class Realms extends AbstractLifecycleComponent<Realms> implements Iterable<Realm> {
public static final Setting<Settings> REALMS_GROUPS_SETTINGS = Setting.groupSetting(setting("authc.realms."), Property.NodeScope);
private final Environment env;
private final Map<String, Realm.Factory> factories;
private final ShieldLicenseState shieldLicenseState;
@ -92,7 +99,7 @@ public class Realms extends AbstractLifecycleComponent<Realms> implements Iterab
}
protected List<Realm> initRealms() {
Settings realmsSettings = settings.getAsSettings("shield.authc.realms");
Settings realmsSettings = REALMS_GROUPS_SETTINGS.get(settings);
Set<String> internalTypes = new HashSet<>();
List<Realm> realms = new ArrayList<>();
for (String name : realmsSettings.names()) {
@ -140,7 +147,7 @@ public class Realms extends AbstractLifecycleComponent<Realms> implements Iterab
* configured, there can only be one configured instance.
*/
public static Settings fileRealmSettings(Settings settings) {
Settings realmsSettings = settings.getAsSettings("shield.authc.realms");
Settings realmsSettings = REALMS_GROUPS_SETTINGS.get(settings);
Settings result = null;
for (String name : realmsSettings.names()) {
Settings realmSettings = realmsSettings.getAsSettings(name);
@ -164,9 +171,13 @@ public class Realms extends AbstractLifecycleComponent<Realms> implements Iterab
if (indexRealmFactory != null) {
realms.add(indexRealmFactory.createDefault("default_" + NativeRealm.TYPE));
}
Realm.Factory esUsersRealm = factories.get(FileRealm.TYPE);
if (esUsersRealm != null) {
realms.add(esUsersRealm.createDefault("default_" + FileRealm.TYPE));
Realm.Factory fileRealm = factories.get(FileRealm.TYPE);
if (fileRealm != null) {
realms.add(fileRealm.createDefault("default_" + FileRealm.TYPE));
}
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(REALMS_GROUPS_SETTINGS);
}
}

View File

@ -6,7 +6,10 @@
package org.elasticsearch.shield.authc.esnative;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.User;
import org.elasticsearch.shield.authc.Realm;
@ -81,5 +84,4 @@ public class NativeRealm extends CachingUsernamePasswordRealm {
return create(config);
}
}
}

View File

@ -36,7 +36,10 @@ import org.elasticsearch.common.ValidationException;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.Provider;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.gateway.GatewayService;
@ -71,6 +74,8 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.elasticsearch.shield.Security.setting;
/**
* ESNativeUsersStore is a {@code UserStore} that, instead of reading from a
* file, reads from an Elasticsearch index instead. This {@code UserStore} in
@ -82,6 +87,15 @@ import java.util.concurrent.atomic.AtomicReference;
*/
public class NativeUsersStore extends AbstractComponent implements ClusterStateListener {
public static final Setting<Integer> SCROLL_SIZE_SETTING =
Setting.intSetting(setting("authc.native.scroll.size"), 1000, Property.NodeScope);
public static final Setting<TimeValue> SCROLL_KEEP_ALIVE_SETTING =
Setting.timeSetting(setting("authc.native.scroll.keep_alive"), TimeValue.timeValueSeconds(10L), Property.NodeScope);
public static final Setting<TimeValue> POLL_INTERVAL_SETTING =
Setting.timeSetting(setting("authc.native.reload.interval"), TimeValue.timeValueSeconds(30L), Property.NodeScope);
public enum State {
INITIALIZED,
STARTING,
@ -445,8 +459,8 @@ public class NativeUsersStore extends AbstractComponent implements ClusterStateL
try {
if (state.compareAndSet(State.INITIALIZED, State.STARTING)) {
this.client = clientProvider.get();
this.scrollSize = settings.getAsInt("shield.authc.native.scroll.size", 1000);
this.scrollKeepAlive = settings.getAsTime("shield.authc.native.scroll.keep_alive", TimeValue.timeValueSeconds(10L));
this.scrollSize = SCROLL_SIZE_SETTING.get(settings);
this.scrollKeepAlive = SCROLL_KEEP_ALIVE_SETTING.get(settings);
// FIXME only start if a realm is using this
UserStorePoller poller = new UserStorePoller();
@ -455,8 +469,7 @@ public class NativeUsersStore extends AbstractComponent implements ClusterStateL
} catch (Exception e) {
logger.warn("failed to do initial poll of users", e);
}
userPoller = new SelfReschedulingRunnable(poller, threadPool,
settings.getAsTime("shield.authc.native.reload.interval", TimeValue.timeValueSeconds(30L)), Names.GENERIC, logger);
userPoller = new SelfReschedulingRunnable(poller, threadPool, POLL_INTERVAL_SETTING.get(settings), Names.GENERIC, logger);
userPoller.start();
state.set(State.STARTED);
}
@ -727,4 +740,10 @@ public class NativeUsersStore extends AbstractComponent implements ClusterStateL
void onUsersChanged(List<String> username);
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(SCROLL_SIZE_SETTING);
settingsModule.registerSetting(SCROLL_KEEP_ALIVE_SETTING);
settingsModule.registerSetting(POLL_INTERVAL_SETTING);
}
}

View File

@ -172,9 +172,9 @@ public class FileUserPasswdStore {
return unmodifiableMap(users);
}
public static void writeFile(Map<String, char[]> esUsers, Path path) {
public static void writeFile(Map<String, char[]> users, Path path) {
try (PrintWriter writer = new PrintWriter(openAtomicMoveWriter(path))) {
for (Map.Entry<String, char[]> entry : esUsers.entrySet()) {
for (Map.Entry<String, char[]> entry : users.entrySet()) {
writer.printf(Locale.ROOT, "%s:%s%s", entry.getKey(), new String(entry.getValue()), System.lineSeparator());
}
} catch (IOException ioe) {

View File

@ -96,9 +96,9 @@ public class UsersTool extends MultiCommand {
char[] password = parsePassword(terminal, passwordOption.value(options));
String[] roles = parseRoles(terminal, env, rolesOption.value(options));
Settings esusersSettings = Realms.fileRealmSettings(env.settings());
Path passwordFile = FileUserPasswdStore.resolveFile(esusersSettings, env);
Path rolesFile = FileUserRolesStore.resolveFile(esusersSettings, env);
Settings fileSettings = Realms.fileRealmSettings(env.settings());
Path passwordFile = FileUserPasswdStore.resolveFile(fileSettings, env);
Path rolesFile = FileUserRolesStore.resolveFile(fileSettings, env);
FileAttributesChecker attributesChecker = new FileAttributesChecker(passwordFile, rolesFile);
Map<String, char[]> users = new HashMap<>(FileUserPasswdStore.parseFile(passwordFile, null));
@ -144,9 +144,9 @@ public class UsersTool extends MultiCommand {
@Override
protected void execute(Terminal terminal, OptionSet options) throws Exception {
String username = parseUsername(arguments.values(options));
Settings esusersSettings = Realms.fileRealmSettings(env.settings());
Path passwordFile = FileUserPasswdStore.resolveFile(esusersSettings, env);
Path rolesFile = FileUserRolesStore.resolveFile(esusersSettings, env);
Settings fileSettings = Realms.fileRealmSettings(env.settings());
Path passwordFile = FileUserPasswdStore.resolveFile(fileSettings, env);
Path rolesFile = FileUserRolesStore.resolveFile(fileSettings, env);
FileAttributesChecker attributesChecker = new FileAttributesChecker(passwordFile, rolesFile);
Map<String, char[]> users = new HashMap<>(FileUserPasswdStore.parseFile(passwordFile, null));
@ -203,8 +203,8 @@ public class UsersTool extends MultiCommand {
String username = parseUsername(arguments.values(options));
char[] password = parsePassword(terminal, passwordOption.value(options));
Settings esusersSettings = Realms.fileRealmSettings(env.settings());
Path file = FileUserPasswdStore.resolveFile(esusersSettings, env);
Settings fileSettings = Realms.fileRealmSettings(env.settings());
Path file = FileUserPasswdStore.resolveFile(fileSettings, env);
FileAttributesChecker attributesChecker = new FileAttributesChecker(file);
Map<String, char[]> users = new HashMap<>(FileUserPasswdStore.parseFile(file, null));
if (users.containsKey(username) == false) {
@ -258,9 +258,9 @@ public class UsersTool extends MultiCommand {
return;
}
Settings esusersSettings = Realms.fileRealmSettings(env.settings());
Path usersFile = FileUserPasswdStore.resolveFile(esusersSettings, env);
Path rolesFile = FileUserRolesStore.resolveFile(esusersSettings, env);
Settings fileSettings = Realms.fileRealmSettings(env.settings());
Path usersFile = FileUserPasswdStore.resolveFile(fileSettings, env);
Path rolesFile = FileUserRolesStore.resolveFile(fileSettings, env);
FileAttributesChecker attributesChecker = new FileAttributesChecker(usersFile, rolesFile);
Map<String, char[]> usersMap = FileUserPasswdStore.parseFile(usersFile, null);
@ -318,11 +318,11 @@ public class UsersTool extends MultiCommand {
// pkg private for tests
static void listUsersAndRoles(Terminal terminal, Environment env, String username) throws Exception {
Settings esusersSettings = Realms.fileRealmSettings(env.settings());
Path userRolesFilePath = FileUserRolesStore.resolveFile(esusersSettings, env);
Settings fileSettings = Realms.fileRealmSettings(env.settings());
Path userRolesFilePath = FileUserRolesStore.resolveFile(fileSettings, env);
Map<String, String[]> userRoles = FileUserRolesStore.parseFile(userRolesFilePath, null);
Path userFilePath = FileUserPasswdStore.resolveFile(esusersSettings, env);
Path userFilePath = FileUserPasswdStore.resolveFile(fileSettings, env);
Set<String> users = FileUserPasswdStore.parseFile(userFilePath, null).keySet();
Path rolesFilePath = FileRolesStore.resolveFile(env.settings(), env);
@ -341,7 +341,7 @@ public class UsersTool extends MultiCommand {
"-" : s).collect(Collectors.joining(","))));
if (!unknownRoles.isEmpty()) {
// at least one role is marked... so printing the legend
Path rolesFile = FileRolesStore.resolveFile(esusersSettings, env).toAbsolutePath();
Path rolesFile = FileRolesStore.resolveFile(fileSettings, env).toAbsolutePath();
terminal.println("");
terminal.println(" [*] An unknown role. "
+ "Please check [" + rolesFile.toAbsolutePath() + "] to see available roles");
@ -375,7 +375,7 @@ public class UsersTool extends MultiCommand {
if (unknownRolesFound) {
// at least one role is marked... so printing the legend
Path rolesFile = FileRolesStore.resolveFile(esusersSettings, env).toAbsolutePath();
Path rolesFile = FileRolesStore.resolveFile(fileSettings, env).toAbsolutePath();
terminal.println("");
terminal.println(" [*] An unknown role. "
+ "Please check [" + rolesFile.toAbsolutePath() + "] to see available roles");
@ -462,8 +462,8 @@ public class UsersTool extends MultiCommand {
}
}
Settings esusersSettings = Realms.fileRealmSettings(env.settings());
verifyRoles(terminal, esusersSettings, env, roles);
Settings fileSettings = Realms.fileRealmSettings(env.settings());
verifyRoles(terminal, fileSettings, env, roles);
return roles;
}

View File

@ -11,6 +11,7 @@ import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.User;
import org.elasticsearch.shield.authc.AuthenticationToken;
import org.elasticsearch.shield.authc.Realm;
@ -194,17 +195,16 @@ public class PkiRealm extends Realm<X509AuthenticationToken> {
static void checkSSLEnabled(RealmConfig config, ESLogger logger) {
Settings settings = config.globalSettings();
final boolean httpSsl = ShieldNettyHttpServerTransport.SSL_SETTING.get(settings);
final boolean httpClientAuth = ShieldNettyHttpServerTransport.CLIENT_AUTH_SETTING.get(settings).enabled();
// HTTP
if (settings.getAsBoolean(ShieldNettyHttpServerTransport.HTTP_SSL_SETTING, ShieldNettyHttpServerTransport.HTTP_SSL_DEFAULT)
&& SSLClientAuth.parse(settings.get(ShieldNettyHttpServerTransport.HTTP_CLIENT_AUTH_SETTING),
ShieldNettyHttpServerTransport.HTTP_CLIENT_AUTH_DEFAULT).enabled()) {
if (httpSsl && httpClientAuth) {
return;
}
// Default Transport
final boolean ssl = settings.getAsBoolean(ShieldNettyTransport.TRANSPORT_SSL_SETTING, ShieldNettyTransport.TRANSPORT_SSL_DEFAULT);
final SSLClientAuth clientAuth = SSLClientAuth.parse(settings.get(ShieldNettyTransport.TRANSPORT_CLIENT_AUTH_SETTING),
ShieldNettyTransport.TRANSPORT_CLIENT_AUTH_DEFAULT);
final boolean ssl = ShieldNettyTransport.SSL_SETTING.get(settings);
final SSLClientAuth clientAuth = ShieldNettyTransport.CLIENT_AUTH_SETTING.get(settings);
if (ssl && clientAuth.enabled()) {
return;
}
@ -212,9 +212,9 @@ public class PkiRealm extends Realm<X509AuthenticationToken> {
// Transport Profiles
Map<String, Settings> groupedSettings = settings.getGroups("transport.profiles.");
for (Map.Entry<String, Settings> entry : groupedSettings.entrySet()) {
Settings profileSettings = entry.getValue().getByPrefix("shield.filter.");
if (profileSettings.getAsBoolean(ShieldNettyTransport.TRANSPORT_PROFILE_SSL_SETTING, ssl)
&& SSLClientAuth.parse(profileSettings.get(ShieldNettyTransport.TRANSPORT_CLIENT_AUTH_SETTING), clientAuth).enabled()) {
Settings profileSettings = entry.getValue().getByPrefix(Security.settingPrefix());
if (ShieldNettyTransport.profileSsl(profileSettings, settings)
&& ShieldNettyTransport.CLIENT_AUTH_SETTING.get(profileSettings, settings).enabled()) {
return;
}
}

View File

@ -6,7 +6,6 @@
package org.elasticsearch.shield.authz;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.shield.authc.esnative.NativeUsersStore;
import org.elasticsearch.shield.authz.store.CompositeRolesStore;
import org.elasticsearch.shield.authz.store.FileRolesStore;
import org.elasticsearch.shield.authz.store.NativeRolesStore;
@ -30,7 +29,6 @@ public class AuthorizationModule extends AbstractShieldModule.Node {
bind(NativeRolesStore.class).asEagerSingleton();
// Then the composite roles store (which combines both) can be bound
bind(RolesStore.class).to(CompositeRolesStore.class).asEagerSingleton();
bind(NativeUsersStore.class).asEagerSingleton();
bind(AuthorizationService.class).to(InternalAuthorizationService.class).asEagerSingleton();
}

View File

@ -11,11 +11,14 @@ import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.yaml.YamlXContent;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.SystemUser;
import org.elasticsearch.shield.XPackUser;
import org.elasticsearch.shield.authc.support.RefreshListener;
@ -42,12 +45,15 @@ import java.util.regex.Pattern;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.shield.Security.setting;
/**
*
*/
public class FileRolesStore extends AbstractLifecycleComponent<RolesStore> implements RolesStore {
public static final Setting<String> ROLES_FILE_SETTING =
Setting.simpleString(setting("authz.store.files.roles"), Property.NodeScope);
private static final Pattern IN_SEGMENT_LINE = Pattern.compile("^\\s+.+");
private static final Pattern SKIP_LINE = Pattern.compile("(^#.*|^\\s*)");
@ -96,12 +102,12 @@ public class FileRolesStore extends AbstractLifecycleComponent<RolesStore> imple
}
public static Path resolveFile(Settings settings, Environment env) {
String location = settings.get("shield.authz.store.files.roles");
if (location == null) {
String location = ROLES_FILE_SETTING.get(settings);
if (location.isEmpty()) {
return XPackPlugin.resolveConfigFile(env, "roles.yml");
}
return env.binFile().getParent().resolve(location);
return XPackPlugin.resolveConfigFile(env, location);
}
public static Set<String> parseFileForRoleNames(Path path, ESLogger logger) {
@ -173,10 +179,10 @@ public class FileRolesStore extends AbstractLifecycleComponent<RolesStore> imple
// first check if FLS/DLS is enabled on the role...
for (RoleDescriptor.IndicesPrivileges privilege : descriptor.getIndicesPrivileges()) {
if ((privilege.getQuery() != null || privilege.getFields() != null)
&& Shield.flsDlsEnabled(settings) == false) {
&& Security.flsDlsEnabled(settings) == false) {
logger.error("invalid role definition [{}] in roles file [{}]. document and field level security is not " +
"enabled. set [{}] to [true] in the configuration file. skipping role...", roleName, path
.toAbsolutePath(), XPackPlugin.featureEnabledSetting(Shield.DLS_FLS_FEATURE));
.toAbsolutePath(), XPackPlugin.featureEnabledSetting(Security.DLS_FLS_FEATURE));
return null;
}
}
@ -255,4 +261,8 @@ public class FileRolesStore extends AbstractLifecycleComponent<RolesStore> imple
}
}
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(ROLES_FILE_SETTING);
}
}

View File

@ -27,7 +27,10 @@ import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.Provider;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.common.xcontent.ToXContent;
@ -64,6 +67,7 @@ import java.util.function.BiFunction;
import java.util.function.Function;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.shield.Security.setting;
/**
* ESNativeRolesStore is a {@code RolesStore} that, instead of reading from a
@ -75,6 +79,15 @@ import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
*/
public class NativeRolesStore extends AbstractComponent implements RolesStore, ClusterStateListener {
public static final Setting<Integer> SCROLL_SIZE_SETTING =
Setting.intSetting(setting("authz.store.roles.index.scroll.size"), 1000, Property.NodeScope);
public static final Setting<TimeValue> SCROLL_KEEP_ALIVE_SETTING =
Setting.timeSetting(setting("authz.store.roles.index.scroll.keep_alive"), TimeValue.timeValueSeconds(10L), Property.NodeScope);
public static final Setting<TimeValue> POLL_INTERVAL_SETTING =
Setting.timeSetting(setting("authz.store.roles.index.reload.interval"), TimeValue.timeValueSeconds(30L), Property.NodeScope);
public enum State {
INITIALIZED,
STARTING,
@ -133,9 +146,9 @@ public class NativeRolesStore extends AbstractComponent implements RolesStore, C
if (state.compareAndSet(State.INITIALIZED, State.STARTING)) {
this.client = clientProvider.get();
this.securityClient = new SecurityClient(client);
this.scrollSize = settings.getAsInt("shield.authc.native.scroll.size", 1000);
this.scrollKeepAlive = settings.getAsTime("shield.authc.native.scroll.keep_alive", TimeValue.timeValueSeconds(10L));
TimeValue pollInterval = settings.getAsTime("shield.authc.native.reload.interval", TimeValue.timeValueSeconds(30L));
this.scrollSize = SCROLL_SIZE_SETTING.get(settings);
this.scrollKeepAlive = SCROLL_KEEP_ALIVE_SETTING.get(settings);
TimeValue pollInterval = POLL_INTERVAL_SETTING.get(settings);
RolesStorePoller poller = new RolesStorePoller();
try {
poller.doRun();
@ -589,4 +602,10 @@ public class NativeRolesStore extends AbstractComponent implements RolesStore, C
return version;
}
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(SCROLL_SIZE_SETTING);
settingsModule.registerSetting(SCROLL_KEEP_ALIVE_SETTING);
settingsModule.registerSetting(POLL_INTERVAL_SETTING);
}
}

View File

@ -10,7 +10,10 @@ import org.elasticsearch.common.Base64;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.authc.support.CharArrays;
import org.elasticsearch.watcher.FileChangesListener;
@ -43,13 +46,13 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Pattern;
import static org.elasticsearch.shield.authc.support.SecuredString.constantTimeEquals;
import static org.elasticsearch.shield.Security.setting;
/**
*
*/
public class InternalCryptoService extends AbstractLifecycleComponent<InternalCryptoService> implements CryptoService {
public static final String FILE_SETTING = "shield.system_key.file";
public static final String KEY_ALGO = "HmacSHA512";
public static final int KEY_SIZE = 1024;
@ -65,6 +68,14 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
private static final Pattern SIG_PATTERN = Pattern.compile("^\\$\\$[0-9]+\\$\\$[^\\$]*\\$\\$.+");
private static final byte[] HKDF_APP_INFO = "es-shield-crypto-service".getBytes(StandardCharsets.UTF_8);
public static final Setting<String> FILE_SETTING = Setting.simpleString(setting("system_key.file"), Property.NodeScope);
public static final Setting<String> ENCRYPTION_ALGO_SETTING =
new Setting<>(setting("encryption.algorithm"), s -> DEFAULT_ENCRYPTION_ALGORITHM, s -> s, Property.NodeScope);
public static final Setting<Integer> ENCRYPTION_KEY_LENGTH_SETTING =
Setting.intSetting(setting("encryption_key.length"), DEFAULT_KEY_LENGTH, Property.NodeScope);
public static final Setting<String> ENCRYPTION_KEY_ALGO_SETTING =
new Setting<>(setting("encryption_key.algorithm"), DEFAULT_KEY_ALGORITH, s -> s, Property.NodeScope);
private final Environment env;
private final ResourceWatcherService watcherService;
private final List<Listener> listeners;
@ -93,10 +104,10 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
this.env = env;
this.watcherService = watcherService;
this.listeners = new CopyOnWriteArrayList<>(listeners);
this.encryptionAlgorithm = settings.get("shield.encryption.algorithm", DEFAULT_ENCRYPTION_ALGORITHM);
this.keyLength = settings.getAsInt("shield.encryption_key.length", DEFAULT_KEY_LENGTH);
this.encryptionAlgorithm = ENCRYPTION_ALGO_SETTING.get(settings);
this.keyLength = ENCRYPTION_KEY_LENGTH_SETTING.get(settings);
this.ivLength = keyLength / 8;
this.keyAlgorithm = settings.get("shield.encryption_key.algorithm", DEFAULT_KEY_ALGORITH);
this.keyAlgorithm = ENCRYPTION_KEY_ALGO_SETTING.get(settings);
}
@Override
@ -157,11 +168,11 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
}
public static Path resolveSystemKey(Settings settings, Environment env) {
String location = settings.get(FILE_SETTING);
if (location == null) {
String location = FILE_SETTING.get(settings);
if (location.isEmpty()) {
return XPackPlugin.resolveConfigFile(env, FILE_NAME);
}
return env.binFile().getParent().resolve(location);
return XPackPlugin.resolveConfigFile(env, location);
}
static SecretKey createSigningKey(@Nullable SecretKey systemKey, SecretKey randomKey) {
@ -668,4 +679,11 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
return result;
}
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(FILE_SETTING);
settingsModule.registerSetting(ENCRYPTION_KEY_LENGTH_SETTING);
settingsModule.registerSetting(ENCRYPTION_KEY_ALGO_SETTING);
settingsModule.registerSetting(ENCRYPTION_ALGO_SETTING);
}
}

View File

@ -13,7 +13,7 @@ import org.elasticsearch.license.core.License;
import org.elasticsearch.license.plugin.core.AbstractLicenseeComponent;
import org.elasticsearch.license.plugin.core.Licensee;
import org.elasticsearch.license.plugin.core.LicenseeRegistry;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
/**
*
@ -25,7 +25,7 @@ public class ShieldLicensee extends AbstractLicenseeComponent<ShieldLicensee> im
@Inject
public ShieldLicensee(Settings settings, LicenseeRegistry clientService, ShieldLicenseState shieldLicenseState) {
super(settings, Shield.NAME, clientService);
super(settings, Security.NAME, clientService);
this.shieldLicenseState = shieldLicenseState;
this.isTribeNode = settings.getGroups("tribe", true).isEmpty() == false;
}

View File

@ -19,7 +19,6 @@ import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.shield.authc.AuthenticationService;
import org.elasticsearch.shield.authc.pki.PkiRealm;
import org.elasticsearch.shield.license.ShieldLicenseState;
import org.elasticsearch.shield.transport.SSLClientAuth;
import org.elasticsearch.shield.transport.netty.ShieldNettyHttpServerTransport;
import org.elasticsearch.threadpool.ThreadPool;
import org.jboss.netty.handler.ssl.SslHandler;
@ -46,10 +45,8 @@ public class ShieldRestFilter extends RestFilter {
this.licenseState = licenseState;
this.threadContext = threadPool.getThreadContext();
controller.registerFilter(this);
boolean ssl = settings.getAsBoolean(ShieldNettyHttpServerTransport.HTTP_SSL_SETTING,
ShieldNettyHttpServerTransport.HTTP_SSL_DEFAULT);
extractClientCertificate = ssl && SSLClientAuth.parse(settings.get(ShieldNettyHttpServerTransport.HTTP_CLIENT_AUTH_SETTING),
ShieldNettyHttpServerTransport.HTTP_CLIENT_AUTH_DEFAULT).enabled();
boolean ssl = ShieldNettyHttpServerTransport.SSL_SETTING.get(settings);
extractClientCertificate = ssl && ShieldNettyHttpServerTransport.CLIENT_AUTH_SETTING.get(settings).enabled();
logger = Loggers.getLogger(getClass(), settings);
}

View File

@ -20,7 +20,7 @@ import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.shield.ShieldBuild;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.license.ShieldLicenseState;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -38,7 +38,7 @@ public class RestShieldInfoAction extends BaseRestHandler {
super(settings, client);
this.clusterName = clusterName;
this.shieldLicenseState = licenseState;
this.shieldEnabled = Shield.enabled(settings);
this.shieldEnabled = Security.enabled(settings);
controller.registerHandler(GET, "/_shield", this);
controller.registerHandler(HEAD, "/_shield", this);
}

View File

@ -6,9 +6,8 @@
package org.elasticsearch.shield.ssl;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
@ -40,17 +39,6 @@ import java.util.concurrent.ConcurrentHashMap;
*/
public abstract class AbstractSSLService extends AbstractComponent {
public static final String CIPHERS_SETTING = "shield.ssl.ciphers";
public static final String SUPPORTED_PROTOCOLS_SETTING = "shield.ssl.supported_protocols";
public static final String[] DEFAULT_SUPPORTED_PROTOCOLS = new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"};
static final String[] DEFAULT_CIPHERS = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"};
static final TimeValue DEFAULT_SESSION_CACHE_TIMEOUT = TimeValue.timeValueHours(24);
static final int DEFAULT_SESSION_CACHE_SIZE = 1000;
static final String DEFAULT_PROTOCOL = "TLSv1.2";
private final ConcurrentHashMap<SSLSettings, SSLContext> sslContexts = new ConcurrentHashMap<>();
private final SSLContextCacheLoader cacheLoader = new SSLContextCacheLoader();
protected Environment env;
@ -70,11 +58,11 @@ public abstract class AbstractSSLService extends AbstractComponent {
}
public String[] supportedProtocols() {
return settings.getAsArray(SUPPORTED_PROTOCOLS_SETTING, DEFAULT_SUPPORTED_PROTOCOLS);
return SSLSettings.Globals.SUPPORTED_PROTOCOLS_SETTING.get(settings).toArray(Strings.EMPTY_ARRAY);
}
public String[] ciphers() {
return settings.getAsArray(CIPHERS_SETTING, DEFAULT_CIPHERS);
return SSLSettings.Globals.CIPHERS_SETTING.get(settings).toArray(Strings.EMPTY_ARRAY);
}
public SSLEngine createSSLEngine() {
@ -86,8 +74,9 @@ public abstract class AbstractSSLService extends AbstractComponent {
}
public SSLEngine createSSLEngine(Settings settings, String host, int port) {
String[] ciphers = settings.getAsArray(CIPHERS_SETTING, ciphers());
String[] supportedProtocols = settings.getAsArray(SUPPORTED_PROTOCOLS_SETTING, supportedProtocols());
String[] ciphers = SSLSettings.Globals.CIPHERS_SETTING.get(settings, this.settings).toArray(Strings.EMPTY_ARRAY);
String[] supportedProtocols = SSLSettings.Globals.SUPPORTED_PROTOCOLS_SETTING.get(settings, this.settings)
.toArray(Strings.EMPTY_ARRAY);
return createSSLEngine(sslContext(settings), ciphers, supportedProtocols, host, port);
}
@ -101,26 +90,6 @@ public abstract class AbstractSSLService extends AbstractComponent {
cacheLoader.load(theSettings));
}
/**
* @return The list of sensitive settings. (these settings shouldnot be exposed via rest API for example)
*/
public static String[] sensitiveSettings() {
return new String[]{
CIPHERS_SETTING,
SUPPORTED_PROTOCOLS_SETTING,
"protocol",
"session.cache_size",
"session.cache_timeout",
"keystore.path",
"keystore.password",
"keystore.algorithm",
"keystore.key_password",
"truststore.path",
"truststore.password",
"truststore.algorithm"
};
}
protected abstract SSLSettings sslSettings(Settings customSettings);
SSLEngine createSSLEngine(SSLContext sslContext, String[] ciphers, String[] supportedProtocols, String host, int port) {
@ -258,87 +227,6 @@ public abstract class AbstractSSLService extends AbstractComponent {
}
public static class SSLSettings {
private static final ESLogger logger = Loggers.getLogger(SSLSettings.class);
String keyStorePath;
String keyStorePassword;
String keyStoreAlgorithm;
String keyPassword;
String trustStorePath;
String trustStorePassword;
String trustStoreAlgorithm;
String sslProtocol;
int sessionCacheSize;
TimeValue sessionCacheTimeout;
SSLSettings(Settings settings, Settings sslServiceSettings) {
keyStorePath = settings.get("keystore.path", sslServiceSettings.get("shield.ssl.keystore.path",
System.getProperty("javax.net.ssl.keyStore")));
keyStorePassword = settings.get("keystore.password", sslServiceSettings.get("shield.ssl.keystore.password",
System.getProperty("javax.net.ssl.keyStorePassword")));
keyStoreAlgorithm = settings.get("keystore.algorithm", sslServiceSettings.get("shield.ssl.keystore.algorithm",
System.getProperty("ssl.KeyManagerFactory.algorithm", KeyManagerFactory.getDefaultAlgorithm())));
keyPassword = settings.get("keystore.key_password",
sslServiceSettings.get("shield.ssl.keystore.key_password", keyStorePassword));
// Truststore settings
trustStorePath = settings.get("truststore.path", sslServiceSettings.get("shield.ssl.truststore.path",
System.getProperty("javax.net.ssl.trustStore")));
trustStorePassword = settings.get("truststore.password", sslServiceSettings.get("shield.ssl.truststore.password",
System.getProperty("javax.net.ssl.trustStorePassword")));
trustStoreAlgorithm = settings.get("truststore.algorithm", sslServiceSettings.get("shield.ssl.truststore.algorithm",
System.getProperty("ssl.TrustManagerFactory.algorithm", TrustManagerFactory.getDefaultAlgorithm())));
sslProtocol = settings.get("protocol", sslServiceSettings.get("shield.ssl.protocol", DEFAULT_PROTOCOL));
sessionCacheSize = settings.getAsInt("session.cache_size",
sslServiceSettings.getAsInt("shield.ssl.session.cache_size", DEFAULT_SESSION_CACHE_SIZE));
sessionCacheTimeout = settings.getAsTime("session.cache_timeout",
sslServiceSettings.getAsTime("shield.ssl.session.cache_timeout", DEFAULT_SESSION_CACHE_TIMEOUT));
if (trustStorePath == null) {
if (logger.isDebugEnabled()) {
logger.debug("no truststore defined. using keystore [{}] as truststore", keyStorePath);
}
trustStorePath = keyStorePath;
trustStorePassword = keyStorePassword;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SSLSettings that = (SSLSettings) o;
if (keyStorePath != null ? !keyStorePath.equals(that.keyStorePath) : that.keyStorePath != null) {
return false;
}
if (sslProtocol != null ? !sslProtocol.equals(that.sslProtocol) : that.sslProtocol != null) {
return false;
}
if (trustStorePath != null ? !trustStorePath.equals(that.trustStorePath) : that.trustStorePath != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = keyStorePath != null ? keyStorePath.hashCode() : 0;
result = 31 * result + (trustStorePath != null ? trustStorePath.hashCode() : 0);
result = 31 * result + (sslProtocol != null ? sslProtocol.hashCode() : 0);
return result;
}
}
/**
* This socket factory set the protocols and ciphers on each SSLSocket after it is created
*/

View File

@ -35,6 +35,7 @@ public class ClientSSLService extends AbstractSSLService {
if (sslSettings.keyStorePassword == null) {
throw new IllegalArgumentException("no keystore password configured");
}
assert sslSettings.keyPassword != null;
}
if (sslSettings.trustStorePath != null) {

View File

@ -0,0 +1,180 @@
/*
* 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.shield.ssl;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.unit.TimeValue;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import static org.elasticsearch.shield.Security.setting;
import static org.elasticsearch.shield.support.OptionalStringSetting.create;
/**
* Class that contains all settings related to SSL
*/
public class SSLSettings {
public interface Globals {
List<String> DEFAULT_SUPPORTED_PROTOCOLS = Arrays.asList("TLSv1", "TLSv1.1", "TLSv1.2");
List<String> DEFAULT_CIPHERS =
Arrays.asList("TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
TimeValue DEFAULT_SESSION_CACHE_TIMEOUT = TimeValue.timeValueHours(24);
int DEFAULT_SESSION_CACHE_SIZE = 1000;
String DEFAULT_PROTOCOL = "TLSv1.2";
Setting<List<String>> CIPHERS_SETTING =
Setting.listSetting(setting("ssl.ciphers"), DEFAULT_CIPHERS, Function.identity(), Property.NodeScope, Property.Filtered);
Setting<List<String>> SUPPORTED_PROTOCOLS_SETTING =
Setting.listSetting(setting("ssl.supported_protocols"), DEFAULT_SUPPORTED_PROTOCOLS,
Function.identity(), Property.NodeScope, Property.Filtered);
Setting<Optional<String>> KEYSTORE_PATH_SETTING = create(setting("ssl.keystore.path"),
s -> System.getProperty("javax.net.ssl.keyStore"), Property.NodeScope, Property.Filtered);
Setting<Optional<String>> KEYSTORE_PASSWORD_SETTING = create(setting("ssl.keystore.password"),
s -> System.getProperty("javax.net.ssl.keyStorePassword"), Property.NodeScope, Property.Filtered);
Setting<String> KEYSTORE_ALGORITHM_SETTING =
new Setting<>(setting("ssl.keystore.algorithm"),
s -> System.getProperty("ssl.KeyManagerFactory.algorithm", KeyManagerFactory.getDefaultAlgorithm()),
Function.identity(), Property.NodeScope, Property.Filtered);
Setting<Optional<String>> KEYSTORE_KEY_PASSWORD_SETTING = create(setting("ssl.keystore.key_password"), KEYSTORE_PASSWORD_SETTING,
Property.NodeScope, Property.Filtered);
Setting<Optional<String>> TRUSTSTORE_PATH_SETTING = create(setting("ssl.truststore.path"),
s -> System.getProperty("javax.net.ssl.trustStore"), Property.NodeScope, Property.Filtered);
Setting<Optional<String>> TRUSTSTORE_PASSWORD_SETTING = create(setting("ssl.truststore.password"),
s -> System.getProperty("javax.net.ssl.trustStorePassword"), Property.NodeScope, Property.Filtered);
Setting<String> TRUSTSTORE_ALGORITHM_SETTING =
new Setting<>(setting("ssl.truststore.algorithm"),
s -> System.getProperty("ssl.TrustManagerFactory.algorithm", TrustManagerFactory.getDefaultAlgorithm()),
Function.identity(), Property.NodeScope, Property.Filtered);
Setting<String> PROTOCOL_SETTING =
new Setting<>(setting("ssl.protocol"), DEFAULT_PROTOCOL, Function.identity(), Property.NodeScope, Property.Filtered);
Setting<Integer> SESSION_CACHE_SIZE_SETTING =
Setting.intSetting(setting("ssl.session.cache_size"), DEFAULT_SESSION_CACHE_SIZE, Property.NodeScope, Property.Filtered);
Setting<TimeValue> SESSION_CACHE_TIMEOUT_SETTING =
Setting.timeSetting(setting("ssl.session.cache_timeout"), DEFAULT_SESSION_CACHE_TIMEOUT,
Property.NodeScope, Property.Filtered);
}
private static final ESLogger logger = Loggers.getLogger(SSLSettings.class);
static Setting<Optional<String>> KEYSTORE_PATH_SETTING = create("keystore.path", Globals.KEYSTORE_PATH_SETTING);
static Setting<Optional<String>> KEYSTORE_PASSWORD_SETTING = create("keystore.password", Globals.KEYSTORE_PASSWORD_SETTING);
static Setting<String> KEYSTORE_ALGORITHM_SETTING =
new Setting<>("keystore.algorithm", Globals.KEYSTORE_ALGORITHM_SETTING, s -> s);
//key password fallback should be keystore.key_password -> keystore.password -> global keystore.key_pasword -> global keystore.password
static Setting<Optional<String>> KEY_PASSWORD_FALLBACK = create("keystore.password", Globals.KEYSTORE_KEY_PASSWORD_SETTING);
static Setting<Optional<String>> KEY_PASSWORD_SETTING = create("keystore.key_password", KEY_PASSWORD_FALLBACK);
static Setting<Optional<String>> TRUSTSTORE_PATH_SETTING = create("truststore.path", Globals.TRUSTSTORE_PATH_SETTING);
static Setting<Optional<String>> TRUSTSTORE_PASSWORD_SETTING = create("truststore.password", Globals.TRUSTSTORE_PASSWORD_SETTING);
static Setting<String> TRUSTSTORE_ALGORITHM_SETTING =
new Setting<>("truststore.algorithm", Globals.TRUSTSTORE_ALGORITHM_SETTING, s -> s);
static Setting<String> PROTOCOL_SETTING =
new Setting<>("protocol", Globals.PROTOCOL_SETTING, s -> s);
static Setting<Integer> CACHE_SIZE_SETTING =
new Setting<>("session.cache_size", Globals.SESSION_CACHE_SIZE_SETTING, Integer::parseInt);
static Setting<TimeValue> CACHE_TIMEOUT_SETTING =
Setting.timeSetting("session.cache_timeout", Globals.SESSION_CACHE_TIMEOUT_SETTING);
String keyStorePath;
String keyStorePassword;
String keyStoreAlgorithm;
String keyPassword;
String trustStorePath;
String trustStorePassword;
String trustStoreAlgorithm;
String sslProtocol;
int sessionCacheSize;
TimeValue sessionCacheTimeout;
SSLSettings(Settings settings, Settings sslServiceSettings) {
keyStorePath = getStringOrNull(KEYSTORE_PATH_SETTING, settings, sslServiceSettings);
keyStorePassword = getStringOrNull(KEYSTORE_PASSWORD_SETTING, settings, sslServiceSettings);
keyStoreAlgorithm = KEYSTORE_ALGORITHM_SETTING.get(settings, sslServiceSettings);
keyPassword = getStringOrNull(KEY_PASSWORD_SETTING, settings, sslServiceSettings);
// Truststore settings
trustStorePath = getStringOrNull(TRUSTSTORE_PATH_SETTING, settings, sslServiceSettings);
trustStorePassword = getStringOrNull(TRUSTSTORE_PASSWORD_SETTING, settings, sslServiceSettings);
trustStoreAlgorithm = TRUSTSTORE_ALGORITHM_SETTING.get(settings, sslServiceSettings);
sslProtocol = PROTOCOL_SETTING.get(settings, sslServiceSettings);
sessionCacheSize = CACHE_SIZE_SETTING.get(settings, sslServiceSettings);
sessionCacheTimeout = CACHE_TIMEOUT_SETTING.get(settings, sslServiceSettings);
if (trustStorePath == null) {
if (logger.isDebugEnabled()) {
logger.debug("no truststore defined. using keystore [{}] as truststore", keyStorePath);
}
trustStorePath = keyStorePath;
trustStorePassword = keyStorePassword;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SSLSettings that = (SSLSettings) o;
if (keyStorePath != null ? !keyStorePath.equals(that.keyStorePath) : that.keyStorePath != null) {
return false;
}
if (sslProtocol != null ? !sslProtocol.equals(that.sslProtocol) : that.sslProtocol != null) {
return false;
}
if (trustStorePath != null ? !trustStorePath.equals(that.trustStorePath) : that.trustStorePath != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = keyStorePath != null ? keyStorePath.hashCode() : 0;
result = 31 * result + (trustStorePath != null ? trustStorePath.hashCode() : 0);
result = 31 * result + (sslProtocol != null ? sslProtocol.hashCode() : 0);
return result;
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(Globals.CIPHERS_SETTING);
settingsModule.registerSetting(Globals.SUPPORTED_PROTOCOLS_SETTING);
settingsModule.registerSetting(Globals.KEYSTORE_PATH_SETTING);
settingsModule.registerSetting(Globals.KEYSTORE_PASSWORD_SETTING);
settingsModule.registerSetting(Globals.KEYSTORE_ALGORITHM_SETTING);
settingsModule.registerSetting(Globals.KEYSTORE_KEY_PASSWORD_SETTING);
settingsModule.registerSetting(Globals.TRUSTSTORE_PATH_SETTING);
settingsModule.registerSetting(Globals.TRUSTSTORE_PASSWORD_SETTING);
settingsModule.registerSetting(Globals.TRUSTSTORE_ALGORITHM_SETTING);
settingsModule.registerSetting(Globals.PROTOCOL_SETTING);
settingsModule.registerSetting(Globals.SESSION_CACHE_SIZE_SETTING);
settingsModule.registerSetting(Globals.SESSION_CACHE_TIMEOUT_SETTING);
}
private static String getStringOrNull(Setting<Optional<String>> setting, Settings settings, Settings fallbackSettings) {
// for settings with complicated fallback we need to try to get it first, if not then try the fallback settings
Optional<String> optional = setting.get(settings);
return optional.orElse(setting.get(fallbackSettings).orElse(null));
}
}

View File

@ -26,6 +26,7 @@ public class ServerSSLService extends AbstractSSLService {
if (sslSettings.keyStorePassword == null) {
throw new IllegalArgumentException("no keystore password configured");
}
assert sslSettings.keyPassword != null;
assert sslSettings.trustStorePath != null;
if (sslSettings.trustStorePassword == null) {

View File

@ -9,7 +9,7 @@ import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
/**
*
@ -23,7 +23,7 @@ public abstract class AbstractShieldModule extends AbstractModule {
public AbstractShieldModule(Settings settings) {
this.settings = settings;
this.clientMode = TransportClient.CLIENT_TYPE.equals(settings.get(Client.CLIENT_TYPE_SETTING_S.getKey()));
this.shieldEnabled = Shield.enabled(settings);
this.shieldEnabled = Security.enabled(settings);
}
@Override

View File

@ -7,7 +7,7 @@ package org.elasticsearch.shield.support;
import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
/**
*
@ -19,13 +19,13 @@ public class Exceptions {
public static ElasticsearchSecurityException authenticationError(String msg, Throwable cause, Object... args) {
ElasticsearchSecurityException e = new ElasticsearchSecurityException(msg, RestStatus.UNAUTHORIZED, cause, args);
e.addHeader("WWW-Authenticate", "Basic realm=\"" + Shield.NAME + "\"");
e.addHeader("WWW-Authenticate", "Basic realm=\"" + Security.NAME + "\"");
return e;
}
public static ElasticsearchSecurityException authenticationError(String msg, Object... args) {
ElasticsearchSecurityException e = new ElasticsearchSecurityException(msg, RestStatus.UNAUTHORIZED, args);
e.addHeader("WWW-Authenticate", "Basic realm=\"" + Shield.NAME + "\"");
e.addHeader("WWW-Authenticate", "Basic realm=\"" + Security.NAME + "\"");
return e;
}

View File

@ -0,0 +1,30 @@
/*
* 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.shield.support;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import java.util.Optional;
import java.util.function.Function;
public class OptionalStringSetting {
private OptionalStringSetting() {}
public static Setting<Optional<String>> create(String key, Property... properties) {
return create(key, s -> null, properties);
}
public static Setting<Optional<String>> create(String key, Function<Settings, String> defaultValue, Property... properties) {
return new Setting<>(key, defaultValue, Optional::ofNullable, properties);
}
public static Setting<Optional<String>> create(String key, Setting<Optional<String>> fallback, Property... properties) {
return new Setting<>(key, fallback, Optional::ofNullable, properties);
}
}

View File

@ -44,10 +44,8 @@ public enum SSLClientAuth {
public abstract void configure(SSLEngine engine);
public static SSLClientAuth parse(String value, SSLClientAuth defaultValue) {
if (value == null) {
return defaultValue;
}
public static SSLClientAuth parse(String value) {
assert value != null;
switch (value.toLowerCase(Locale.ROOT)) {
case "no":
case "false":

View File

@ -7,7 +7,6 @@ package org.elasticsearch.shield.transport;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.shield.action.ShieldActionMapper;
@ -35,12 +34,9 @@ import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_CLIENT_AUTH_DEFAULT;
import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_CLIENT_AUTH_SETTING;
import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_PROFILE_CLIENT_AUTH_SETTING;
import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_PROFILE_SSL_SETTING;
import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_SSL_DEFAULT;
import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_SSL_SETTING;
import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.CLIENT_AUTH_SETTING;
import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.PROFILE_CLIENT_AUTH_SETTING;
import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.SSL_SETTING;
/**
*
@ -127,10 +123,8 @@ public class ShieldServerTransportService extends TransportService {
for (Map.Entry<String, Settings> entry : profileSettingsMap.entrySet()) {
Settings profileSettings = entry.getValue();
final boolean profileSsl = profileSettings.getAsBoolean(TRANSPORT_PROFILE_SSL_SETTING,
settings.getAsBoolean(TRANSPORT_SSL_SETTING, TRANSPORT_SSL_DEFAULT));
final boolean clientAuth = SSLClientAuth.parse(profileSettings.get(TRANSPORT_PROFILE_CLIENT_AUTH_SETTING,
settings.get(TRANSPORT_CLIENT_AUTH_SETTING)), TRANSPORT_CLIENT_AUTH_DEFAULT).enabled();
final boolean profileSsl = ShieldNettyTransport.profileSsl(profileSettings, settings);
final boolean clientAuth = PROFILE_CLIENT_AUTH_SETTING.get(profileSettings, settings).enabled();
final boolean extractClientCert = profileSsl && clientAuth;
String type = entry.getValue().get(SETTING_NAME, "node");
switch (type) {
@ -145,9 +139,8 @@ public class ShieldServerTransportService extends TransportService {
}
if (!profileFilters.containsKey(TransportSettings.DEFAULT_PROFILE)) {
final boolean profileSsl = settings.getAsBoolean(TRANSPORT_SSL_SETTING, TRANSPORT_SSL_DEFAULT);
final boolean clientAuth =
SSLClientAuth.parse(settings.get(TRANSPORT_CLIENT_AUTH_SETTING), TRANSPORT_CLIENT_AUTH_DEFAULT).enabled();
final boolean profileSsl = SSL_SETTING.get(settings);
final boolean clientAuth = CLIENT_AUTH_SETTING.get(settings).enabled();
final boolean extractClientCert = profileSsl && clientAuth;
profileFilters.put(TransportSettings.DEFAULT_PROFILE, new ServerTransportFilter.NodeProfile(authcService, authzService,
actionMapper, threadPool.getThreadContext(), extractClientCert));

View File

@ -27,7 +27,7 @@ public class ShieldTransportModule extends AbstractShieldModule {
bind(ClientTransportFilter.class).to(ClientTransportFilter.TransportClient.class).asEagerSingleton();
} else {
bind(ClientTransportFilter.class).to(ClientTransportFilter.Node.class).asEagerSingleton();
if (settings.getAsBoolean("shield.transport.filter.enabled", true)) {
if (IPFilter.IP_FILTER_ENABLED_SETTING.get(settings)) {
bind(IPFilter.class).asEagerSingleton();
}
}

View File

@ -7,13 +7,14 @@ package org.elasticsearch.shield.transport.filter;
import org.apache.lucene.util.SetOnce;
import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.shield.audit.AuditTrail;
@ -30,6 +31,7 @@ import java.util.Map;
import java.util.function.Function;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.shield.Security.setting;
public class IPFilter {
@ -41,24 +43,32 @@ public class IPFilter {
*/
public static final String HTTP_PROFILE_NAME = ".http";
public static final Setting<Boolean> IP_FILTER_ENABLED_HTTP_SETTING = Setting.boolSetting("shield.http.filter.enabled", true,
Setting.Property.Dynamic, Setting.Property.NodeScope);
public static final Setting<Boolean> IP_FILTER_ENABLED_SETTING = new Setting<>("shield.transport.filter.enabled", (s) ->
IP_FILTER_ENABLED_HTTP_SETTING.getDefaultRaw(s), Booleans::parseBooleanExact, Setting.Property.Dynamic,
Setting.Property.NodeScope);
public static final Setting<List<String>> TRANSPORT_FILTER_ALLOW_SETTING = Setting.listSetting("shield.transport.filter.allow",
Collections.emptyList(), Function.identity(), Setting.Property.Dynamic, Setting.Property.NodeScope);
public static final Setting<List<String>> TRANSPORT_FILTER_DENY_SETTING = Setting.listSetting("shield.transport.filter.deny",
Collections.emptyList(), Function.identity(), Setting.Property.Dynamic, Setting.Property.NodeScope);
public static final Setting<Boolean> ALLOW_BOUND_ADDRESSES_SETTING =
Setting.boolSetting(setting("filter.always_allow_bound_address"), true, Property.NodeScope);
public static final Setting<List<String>> HTTP_FILTER_ALLOW_SETTING = Setting.listSetting("shield.http.filter.allow", (s) -> {
return Arrays.asList(s.getAsArray("transport.profiles.default.shield.filter.allow",
TRANSPORT_FILTER_ALLOW_SETTING.get(s).toArray(new String[0])));
}, Function.identity(), Setting.Property.Dynamic, Setting.Property.NodeScope);
public static final Setting<List<String>> HTTP_FILTER_DENY_SETTING = Setting.listSetting("shield.http.filter.deny", (s) -> {
return Arrays.asList(s.getAsArray("transport.profiles.default.shield.filter.deny",
TRANSPORT_FILTER_DENY_SETTING.get(s).toArray(new String[0])));
}, Function.identity(), Setting.Property.Dynamic, Setting.Property.NodeScope);
public static final Setting<Boolean> IP_FILTER_ENABLED_HTTP_SETTING = Setting.boolSetting(setting("http.filter.enabled"),
true, Property.Dynamic, Property.NodeScope);
public static final Setting<Boolean> IP_FILTER_ENABLED_SETTING = Setting.boolSetting(setting("transport.filter.enabled"),
true, Property.Dynamic, Property.NodeScope);
public static final Setting<List<String>> TRANSPORT_FILTER_ALLOW_SETTING = Setting.listSetting(setting("transport.filter.allow"),
Collections.emptyList(), Function.identity(), Property.Dynamic, Property.NodeScope);
public static final Setting<List<String>> TRANSPORT_FILTER_DENY_SETTING = Setting.listSetting(setting("transport.filter.deny"),
Collections.emptyList(), Function.identity(), Property.Dynamic, Property.NodeScope);
private static final Setting<List<String>> HTTP_FILTER_ALLOW_FALLBACK =
Setting.listSetting("transport.profiles.default.xpack.security.filter.allow", TRANSPORT_FILTER_ALLOW_SETTING, s -> s,
Property.NodeScope);
public static final Setting<List<String>> HTTP_FILTER_ALLOW_SETTING = Setting.listSetting(setting("http.filter.allow"),
HTTP_FILTER_ALLOW_FALLBACK, Function.identity(), Property.Dynamic, Property.NodeScope);
private static final Setting<List<String>> HTTP_FILTER_DENY_FALLBACK =
Setting.listSetting("transport.profiles.default.xpack.security.filter.deny", TRANSPORT_FILTER_DENY_SETTING, s -> s,
Property.NodeScope);
public static final Setting<List<String>> HTTP_FILTER_DENY_SETTING = Setting.listSetting(setting("http.filter.deny"),
HTTP_FILTER_DENY_FALLBACK, Function.identity(), Property.Dynamic, Property.NodeScope);
public static final ShieldIpFilterRule DEFAULT_PROFILE_ACCEPT_ALL = new ShieldIpFilterRule(true, "default:accept_all") {
@ -101,7 +111,7 @@ public class IPFilter {
this.logger = Loggers.getLogger(getClass(), settings);
this.auditTrail = auditTrail;
this.licenseState = licenseState;
this.alwaysAllowBoundAddresses = settings.getAsBoolean("shield.filter.always_allow_bound_address", true);
this.alwaysAllowBoundAddresses = ALLOW_BOUND_ADDRESSES_SETTING.get(settings);
httpDenyFilter = HTTP_FILTER_DENY_SETTING.get(settings);
httpAllowFilter = HTTP_FILTER_ALLOW_SETTING.get(settings);
transportAllowFilter = TRANSPORT_FILTER_ALLOW_SETTING.get(settings);
@ -205,7 +215,7 @@ public class IPFilter {
logger.warn("skipping ip filter rules for profile [{}] since the profile is not bound to any addresses", profile);
continue;
}
Settings profileSettings = entry.getValue().getByPrefix("shield.filter.");
Settings profileSettings = entry.getValue().getByPrefix(setting("filter."));
profileRules.put(profile, createRules(Arrays.asList(profileSettings.getAsArray("allow")),
Arrays.asList(profileSettings.getAsArray("deny")), profileBoundTransportAddress.boundAddresses()));
}
@ -249,4 +259,14 @@ public class IPFilter {
this.boundHttpTransportAddress.set(boundHttpTransportAddress);
updateRules();
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(ALLOW_BOUND_ADDRESSES_SETTING);
settingsModule.registerSetting(IP_FILTER_ENABLED_SETTING);
settingsModule.registerSetting(IP_FILTER_ENABLED_HTTP_SETTING);
settingsModule.registerSetting(HTTP_FILTER_ALLOW_SETTING);
settingsModule.registerSetting(HTTP_FILTER_DENY_SETTING);
settingsModule.registerSetting(TRANSPORT_FILTER_ALLOW_SETTING);
settingsModule.registerSetting(TRANSPORT_FILTER_DENY_SETTING);
}
}

View File

@ -7,7 +7,10 @@ package org.elasticsearch.shield.transport.netty;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.network.NetworkService;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.http.netty.NettyHttpServerTransport;
import org.elasticsearch.shield.ssl.ServerSSLService;
@ -22,6 +25,7 @@ import org.jboss.netty.handler.ssl.SslHandler;
import javax.net.ssl.SSLEngine;
import static org.elasticsearch.shield.Security.setting;
import static org.elasticsearch.shield.transport.SSLExceptionHelper.isCloseDuringHandshakeException;
import static org.elasticsearch.shield.transport.SSLExceptionHelper.isNotSslRecordException;
@ -30,10 +34,16 @@ import static org.elasticsearch.shield.transport.SSLExceptionHelper.isNotSslReco
*/
public class ShieldNettyHttpServerTransport extends NettyHttpServerTransport {
public static final String HTTP_SSL_SETTING = "shield.http.ssl";
public static final boolean HTTP_SSL_DEFAULT = false;
public static final String HTTP_CLIENT_AUTH_SETTING = "shield.http.ssl.client.auth";
public static final SSLClientAuth HTTP_CLIENT_AUTH_DEFAULT = SSLClientAuth.NO;
public static final boolean SSL_DEFAULT = false;
public static final String CLIENT_AUTH_DEFAULT = SSLClientAuth.NO.name();
public static final Setting<Boolean> DEPRECATED_SSL_SETTING =
Setting.boolSetting(setting("http.ssl"), SSL_DEFAULT, Property.NodeScope, Property.Deprecated);
public static final Setting<Boolean> SSL_SETTING =
Setting.boolSetting(setting("http.ssl.enabled"), DEPRECATED_SSL_SETTING, Property.NodeScope);
public static final Setting<SSLClientAuth> CLIENT_AUTH_SETTING =
new Setting<>(setting("http.ssl.client.auth"), CLIENT_AUTH_DEFAULT, SSLClientAuth::parse, Property.NodeScope);
private final IPFilter ipFilter;
private final ServerSSLService sslService;
@ -44,7 +54,7 @@ public class ShieldNettyHttpServerTransport extends NettyHttpServerTransport {
IPFilter ipFilter, ServerSSLService sslService, ThreadPool threadPool) {
super(settings, networkService, bigArrays, threadPool);
this.ipFilter = ipFilter;
this.ssl = settings.getAsBoolean(HTTP_SSL_SETTING, HTTP_SSL_DEFAULT);
this.ssl = SSL_SETTING.get(settings);
this.sslService = sslService;
}
@ -91,7 +101,7 @@ public class ShieldNettyHttpServerTransport extends NettyHttpServerTransport {
public HttpSslChannelPipelineFactory(NettyHttpServerTransport transport) {
super(transport, detailedErrorsEnabled, threadPool.getThreadContext());
clientAuth = SSLClientAuth.parse(settings.get(HTTP_CLIENT_AUTH_SETTING), HTTP_CLIENT_AUTH_DEFAULT);
clientAuth = CLIENT_AUTH_SETTING.get(settings);
}
@Override
@ -108,4 +118,10 @@ public class ShieldNettyHttpServerTransport extends NettyHttpServerTransport {
return pipeline;
}
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(SSL_SETTING);
settingsModule.registerSetting(CLIENT_AUTH_SETTING);
settingsModule.registerSetting(DEPRECATED_SSL_SETTING);
}
}

View File

@ -11,7 +11,10 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.internal.Nullable;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.network.NetworkService;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.shield.ssl.ClientSSLService;
import org.elasticsearch.shield.ssl.ServerSSLService;
@ -31,6 +34,8 @@ import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import java.net.InetSocketAddress;
import static org.elasticsearch.shield.Security.setting;
import static org.elasticsearch.shield.Security.settingPrefix;
import static org.elasticsearch.shield.transport.SSLExceptionHelper.isCloseDuringHandshakeException;
import static org.elasticsearch.shield.transport.SSLExceptionHelper.isNotSslRecordException;
@ -39,14 +44,32 @@ import static org.elasticsearch.shield.transport.SSLExceptionHelper.isNotSslReco
*/
public class ShieldNettyTransport extends NettyTransport {
public static final String HOSTNAME_VERIFICATION_SETTING = "shield.ssl.hostname_verification";
public static final String HOSTNAME_VERIFICATION_RESOLVE_NAME_SETTING = "shield.ssl.hostname_verification.resolve_name";
public static final String TRANSPORT_SSL_SETTING = "shield.transport.ssl";
public static final boolean TRANSPORT_SSL_DEFAULT = false;
public static final String TRANSPORT_CLIENT_AUTH_SETTING = "shield.transport.ssl.client.auth";
public static final SSLClientAuth TRANSPORT_CLIENT_AUTH_DEFAULT = SSLClientAuth.REQUIRED;
public static final String TRANSPORT_PROFILE_SSL_SETTING = "shield.ssl";
public static final String TRANSPORT_PROFILE_CLIENT_AUTH_SETTING = "shield.ssl.client.auth";
public static final String CLIENT_AUTH_DEFAULT = SSLClientAuth.REQUIRED.name();
public static final boolean SSL_DEFAULT = false;
public static final Setting<Boolean> HOSTNAME_VERIFICATION_SETTING =
Setting.boolSetting(setting("ssl.hostname_verification"), true, Property.NodeScope, Property.Filtered);
public static final Setting<Boolean> HOSTNAME_VERIFICATION_RESOLVE_NAME_SETTING =
Setting.boolSetting(setting("ssl.hostname_verification.resolve_name"), true, Property.NodeScope, Property.Filtered);
public static final Setting<Boolean> DEPRECATED_SSL_SETTING =
Setting.boolSetting(setting("transport.ssl"), SSL_DEFAULT,
Property.Filtered, Property.NodeScope, Property.Deprecated);
public static final Setting<Boolean> SSL_SETTING =
Setting.boolSetting(setting("transport.ssl.enabled"), DEPRECATED_SSL_SETTING, Property.Filtered, Property.NodeScope);
public static final Setting<SSLClientAuth> CLIENT_AUTH_SETTING =
new Setting<>(setting("transport.ssl.client.auth"), CLIENT_AUTH_DEFAULT,
SSLClientAuth::parse, Property.NodeScope, Property.Filtered);
public static final Setting<Boolean> DEPRECATED_PROFILE_SSL_SETTING =
Setting.boolSetting(setting("ssl"), SSL_SETTING, Property.Filtered, Property.NodeScope, Property.Deprecated);
public static final Setting<Boolean> PROFILE_SSL_SETTING =
Setting.boolSetting(setting("ssl.enabled"), SSL_DEFAULT, Property.Filtered, Property.NodeScope);
public static final Setting<SSLClientAuth> PROFILE_CLIENT_AUTH_SETTING =
new Setting<>(setting("ssl.client.auth"), CLIENT_AUTH_SETTING, SSLClientAuth::parse,
Property.NodeScope, Property.Filtered);
private final ServerSSLService serverSslService;
private final ClientSSLService clientSSLService;
@ -59,7 +82,7 @@ public class ShieldNettyTransport extends NettyTransport {
ClientSSLService clientSSLService, NamedWriteableRegistry namedWriteableRegistry) {
super(settings, threadPool, networkService, bigArrays, version, namedWriteableRegistry);
this.authenticator = authenticator;
this.ssl = settings.getAsBoolean(TRANSPORT_SSL_SETTING, TRANSPORT_SSL_DEFAULT);
this.ssl = SSL_SETTING.get(settings);
this.serverSslService = serverSSLService;
this.clientSSLService = clientSSLService;
}
@ -110,6 +133,18 @@ public class ShieldNettyTransport extends NettyTransport {
}
}
public static boolean profileSsl(Settings profileSettings, Settings settings) {
// we can't use the fallback mechanism here since it may not exist in the profile settings and we get the wrong value
// for the profile if they use the old setting
if (PROFILE_SSL_SETTING.exists(profileSettings)) {
return SSL_SETTING.get(profileSettings);
} else if (DEPRECATED_PROFILE_SSL_SETTING.exists(profileSettings)) {
return DEPRECATED_PROFILE_SSL_SETTING.get(profileSettings);
} else {
return SSL_SETTING.get(settings);
}
}
private class SslServerChannelPipelineFactory extends ServerChannelPipelineFactory {
private final Settings profileSettings;
@ -122,13 +157,13 @@ public class ShieldNettyTransport extends NettyTransport {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = super.getPipeline();
final boolean profileSsl = profileSettings.getAsBoolean(TRANSPORT_PROFILE_SSL_SETTING, ssl);
final SSLClientAuth clientAuth = SSLClientAuth.parse(profileSettings.get(TRANSPORT_PROFILE_CLIENT_AUTH_SETTING,
settings.get(TRANSPORT_CLIENT_AUTH_SETTING)), TRANSPORT_CLIENT_AUTH_DEFAULT);
final boolean profileSsl = profileSsl(profileSettings, settings);
final SSLClientAuth clientAuth = PROFILE_CLIENT_AUTH_SETTING.get(profileSettings, settings);
if (profileSsl) {
SSLEngine serverEngine;
if (profileSettings.get("shield.truststore.path") != null) {
serverEngine = serverSslService.createSSLEngine(profileSettings.getByPrefix("shield."));
Settings securityProfileSettings = profileSettings.getByPrefix(settingPrefix());
if (securityProfileSettings.names().isEmpty() == false) {
serverEngine = serverSslService.createSSLEngine(securityProfileSettings);
} else {
serverEngine = serverSslService.createSSLEngine();
}
@ -168,7 +203,7 @@ public class ShieldNettyTransport extends NettyTransport {
@Override
public void connectRequested(ChannelHandlerContext ctx, ChannelStateEvent e) {
SSLEngine sslEngine;
if (settings.getAsBoolean(HOSTNAME_VERIFICATION_SETTING, true)) {
if (HOSTNAME_VERIFICATION_SETTING.get(settings)) {
InetSocketAddress inetSocketAddress = (InetSocketAddress) e.getValue();
sslEngine = clientSSLService.createSSLEngine(Settings.EMPTY, getHostname(inetSocketAddress),
inetSocketAddress.getPort());
@ -193,7 +228,7 @@ public class ShieldNettyTransport extends NettyTransport {
@SuppressForbidden(reason = "need to use getHostName to resolve DNS name for SSL connections and hostname verification")
private String getHostname(InetSocketAddress inetSocketAddress) {
String hostname;
if (settings.getAsBoolean(HOSTNAME_VERIFICATION_RESOLVE_NAME_SETTING, true)) {
if (HOSTNAME_VERIFICATION_RESOLVE_NAME_SETTING.get(settings)) {
hostname = inetSocketAddress.getHostName();
} else {
hostname = inetSocketAddress.getHostString();
@ -207,4 +242,17 @@ public class ShieldNettyTransport extends NettyTransport {
}
}
}
public static void registerSettings(SettingsModule settingsModule) {
settingsModule.registerSetting(SSL_SETTING);
settingsModule.registerSetting(HOSTNAME_VERIFICATION_SETTING);
settingsModule.registerSetting(HOSTNAME_VERIFICATION_RESOLVE_NAME_SETTING);
settingsModule.registerSetting(CLIENT_AUTH_SETTING);
settingsModule.registerSetting(PROFILE_SSL_SETTING);
settingsModule.registerSetting(PROFILE_CLIENT_AUTH_SETTING);
// deprecated transport settings
settingsModule.registerSetting(DEPRECATED_SSL_SETTING);
settingsModule.registerSetting(DEPRECATED_PROFILE_SSL_SETTING);
}
}

View File

@ -10,7 +10,7 @@ import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.shield.authc.support.UsernamePasswordToken;
import org.elasticsearch.test.ShieldIntegTestCase;
@ -31,7 +31,7 @@ public class BulkUpdateTests extends ShieldIntegTestCase {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(NetworkModule.HTTP_ENABLED.getKey(), true)
.put(XPackPlugin.featureEnabledSetting(Shield.DLS_FLS_FEATURE), randomBoolean())
.put(XPackPlugin.featureEnabledSetting(Security.DLS_FLS_FEATURE), randomBoolean())
.build();
}

View File

@ -16,6 +16,7 @@ import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.shield.action.role.PutRoleResponse;
import org.elasticsearch.shield.action.role.GetRolesResponse;
import org.elasticsearch.shield.ShieldTemplateService;
import org.elasticsearch.shield.authc.esnative.NativeRealm;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.shield.authc.support.UsernamePasswordToken;
import org.elasticsearch.shield.authz.RoleDescriptor;
@ -78,7 +79,7 @@ public class ClearRolesCacheTests extends NativeRealmIntegTestCase {
logger.debug("using poller interval [{}]", pollerInterval);
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put("shield.authc.native.reload.interval", pollerInterval)
.put(NativeRolesStore.POLL_INTERVAL_SETTING.getKey(), pollerInterval)
.put(NetworkModule.HTTP_ENABLED.getKey(), true)
.build();
}

View File

@ -9,7 +9,7 @@ import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexModule;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.Hasher;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.test.ShieldIntegTestCase;
@ -85,7 +85,7 @@ public class DocumentAndFieldLevelSecurityTests extends ShieldIntegTestCase {
public Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(XPackPlugin.featureEnabledSetting(Shield.DLS_FLS_FEATURE), true)
.put(XPackPlugin.featureEnabledSetting(Security.DLS_FLS_FEATURE), true)
.build();
}

View File

@ -10,7 +10,7 @@ import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.Hasher;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.test.ShieldIntegTestCase;
@ -88,7 +88,7 @@ public class DocumentLevelSecurityRandomTests extends ShieldIntegTestCase {
public Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(XPackPlugin.featureEnabledSetting(Shield.DLS_FLS_FEATURE), true)
.put(XPackPlugin.featureEnabledSetting(Security.DLS_FLS_FEATURE), true)
.build();
}

View File

@ -26,7 +26,7 @@ import org.elasticsearch.search.aggregations.bucket.children.Children;
import org.elasticsearch.search.aggregations.bucket.global.Global;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.Hasher;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.test.ShieldIntegTestCase;
@ -100,7 +100,7 @@ public class DocumentLevelSecurityTests extends ShieldIntegTestCase {
public Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(XPackPlugin.featureEnabledSetting(Shield.DLS_FLS_FEATURE), true)
.put(XPackPlugin.featureEnabledSetting(Security.DLS_FLS_FEATURE), true)
.build();
}

View File

@ -10,7 +10,7 @@ import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.Hasher;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.test.ShieldIntegTestCase;
@ -120,7 +120,7 @@ public class FieldLevelSecurityRandomTests extends ShieldIntegTestCase {
public Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(XPackPlugin.featureEnabledSetting(Shield.DLS_FLS_FEATURE), true)
.put(XPackPlugin.featureEnabledSetting(Security.DLS_FLS_FEATURE), true)
.build();
}

View File

@ -24,7 +24,7 @@ import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.Hasher;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.test.ESIntegTestCase;
@ -128,7 +128,7 @@ public class FieldLevelSecurityTests extends ShieldIntegTestCase {
public Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(XPackPlugin.featureEnabledSetting(Shield.DLS_FLS_FEATURE), true)
.put(XPackPlugin.featureEnabledSetting(Security.DLS_FLS_FEATURE), true)
.build();
}

View File

@ -8,7 +8,7 @@ package org.elasticsearch.integration;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.Hasher;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.test.ShieldIntegTestCase;
@ -61,7 +61,7 @@ public class IndicesPermissionsWithAliasesWildcardsAndRegexsTests extends Shield
public Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(XPackPlugin.featureEnabledSetting(Shield.DLS_FLS_FEATURE), true)
.put(XPackPlugin.featureEnabledSetting(Security.DLS_FLS_FEATURE), true)
.build();
}

View File

@ -30,7 +30,7 @@ import org.elasticsearch.license.plugin.core.LicenseState;
import org.elasticsearch.license.plugin.core.Licensee;
import org.elasticsearch.license.plugin.core.LicenseeRegistry;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.UsernamePasswordToken;
import org.elasticsearch.test.ShieldIntegTestCase;
import org.elasticsearch.test.ShieldSettingsSource;
@ -144,7 +144,7 @@ public class LicensingTests extends ShieldIntegTestCase {
fail("expected an license expired exception when executing an index stats action");
} catch (ElasticsearchSecurityException ee) {
// expected
assertThat(ee.getHeader("es.license.expired.feature"), hasItem(Shield.NAME));
assertThat(ee.getHeader("es.license.expired.feature"), hasItem(Security.NAME));
assertThat(ee.status(), is(RestStatus.UNAUTHORIZED));
}
@ -153,7 +153,7 @@ public class LicensingTests extends ShieldIntegTestCase {
fail("expected an license expired exception when executing cluster stats action");
} catch (ElasticsearchSecurityException ee) {
// expected
assertThat(ee.getHeader("es.license.expired.feature"), hasItem(Shield.NAME));
assertThat(ee.getHeader("es.license.expired.feature"), hasItem(Security.NAME));
assertThat(ee.status(), is(RestStatus.UNAUTHORIZED));
}
@ -162,7 +162,7 @@ public class LicensingTests extends ShieldIntegTestCase {
fail("expected an license expired exception when executing cluster health action");
} catch (ElasticsearchSecurityException ee) {
// expected
assertThat(ee.getHeader("es.license.expired.feature"), hasItem(Shield.NAME));
assertThat(ee.getHeader("es.license.expired.feature"), hasItem(Security.NAME));
assertThat(ee.status(), is(RestStatus.UNAUTHORIZED));
}
@ -171,7 +171,7 @@ public class LicensingTests extends ShieldIntegTestCase {
fail("expected an license expired exception when executing cluster health action");
} catch (ElasticsearchSecurityException ee) {
// expected
assertThat(ee.getHeader("es.license.expired.feature"), hasItem(Shield.NAME));
assertThat(ee.getHeader("es.license.expired.feature"), hasItem(Security.NAME));
assertThat(ee.status(), is(RestStatus.UNAUTHORIZED));
}
@ -207,7 +207,7 @@ public class LicensingTests extends ShieldIntegTestCase {
Settings.Builder builder = Settings.builder()
.put(internalCluster().transportClient().settings());
// remove user info
builder.remove("shield.user");
builder.remove(Security.USER_SETTING.getKey());
builder.remove(ThreadContext.PREFIX + "." + UsernamePasswordToken.BASIC_AUTH_HEADER);
// basic has no auth

View File

@ -9,6 +9,7 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.xcontent.XContentBuilder;
@ -19,6 +20,7 @@ import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.shield.authc.support.UsernamePasswordToken;
import org.elasticsearch.shield.ssl.AbstractSSLService;
import org.elasticsearch.shield.ssl.SSLSettings;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ShieldIntegTestCase;
import org.elasticsearch.test.ShieldSettingsSource;
@ -71,10 +73,10 @@ public class SettingsFilterTests extends ShieldIntegTestCase {
}
public void onModule(SettingsModule module) {
module.registerSetting(Setting.simpleString("foo.bar", Setting.Property.NodeScope));
module.registerSetting(Setting.simpleString("foo.baz", Setting.Property.NodeScope));
module.registerSetting(Setting.simpleString("bar.baz", Setting.Property.NodeScope));
module.registerSetting(Setting.simpleString("baz.foo", Setting.Property.NodeScope));
module.registerSetting(Setting.simpleString("foo.bar", Property.NodeScope));
module.registerSetting(Setting.simpleString("foo.baz", Property.NodeScope));
module.registerSetting(Setting.simpleString("bar.baz", Property.NodeScope));
module.registerSetting(Setting.simpleString("baz.foo", Property.NodeScope));
}
}
@ -84,56 +86,57 @@ public class SettingsFilterTests extends ShieldIntegTestCase {
return Settings.builder().put(super.nodeSettings(nodeOrdinal))
.put(NetworkModule.HTTP_ENABLED.getKey(), true)
.put("shield.authc.realms.file.type", "file")
.put("xpack.security.authc.realms.file.type", "file")
// ldap realm filtering
.put("shield.authc.realms.ldap1.type", "ldap")
.put("shield.authc.realms.ldap1.enabled", "false")
.put("shield.authc.realms.ldap1.url", "ldap://host.domain")
.put("shield.authc.realms.ldap1.hostname_verification", randomAsciiOfLength(5))
.put("shield.authc.realms.ldap1.bind_dn", randomAsciiOfLength(5))
.put("shield.authc.realms.ldap1.bind_password", randomAsciiOfLength(5))
.put("xpack.security.authc.realms.ldap1.type", "ldap")
.put("xpack.security.authc.realms.ldap1.enabled", "false")
.put("xpack.security.authc.realms.ldap1.url", "ldap://host.domain")
.put("xpack.security.authc.realms.ldap1.hostname_verification", randomAsciiOfLength(5))
.put("xpack.security.authc.realms.ldap1.bind_dn", randomAsciiOfLength(5))
.put("xpack.security.authc.realms.ldap1.bind_password", randomAsciiOfLength(5))
// active directory filtering
.put("shield.authc.realms.ad1.type", "active_directory")
.put("shield.authc.realms.ad1.enabled", "false")
.put("shield.authc.realms.ad1.url", "ldap://host.domain")
.put("shield.authc.realms.ad1.hostname_verification", randomAsciiOfLength(5))
.put("xpack.security.authc.realms.ad1.type", "active_directory")
.put("xpack.security.authc.realms.ad1.enabled", "false")
.put("xpack.security.authc.realms.ad1.url", "ldap://host.domain")
.put("xpack.security.authc.realms.ad1.hostname_verification", randomAsciiOfLength(5))
// pki filtering
.put("shield.authc.realms.pki1.type", "pki")
.put("shield.authc.realms.pki1.order", "0")
.put("shield.authc.realms.pki1.truststore.path",
.put("xpack.security.authc.realms.pki1.type", "pki")
.put("xpack.security.authc.realms.pki1.order", "0")
.put("xpack.security.authc.realms.pki1.truststore.path",
getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/truststore-testnode-only.jks"))
.put("shield.authc.realms.pki1.truststore.password", "truststore-testnode-only")
.put("shield.authc.realms.pki1.truststore.algorithm", "SunX509")
.put("xpack.security.authc.realms.pki1.truststore.password", "truststore-testnode-only")
.put("xpack.security.authc.realms.pki1.truststore.algorithm", "SunX509")
.put("shield.ssl.keystore.path", "/path/to/keystore")
.put("shield.ssl.ciphers", "_ciphers")
.put("shield.ssl.supported_protocols", randomFrom(AbstractSSLService.DEFAULT_SUPPORTED_PROTOCOLS))
.put("shield.ssl.keystore.password", randomAsciiOfLength(5))
.put("shield.ssl.keystore.algorithm", "_algorithm")
.put("shield.ssl.keystore.key_password", randomAsciiOfLength(5))
.put("shield.ssl.truststore.password", randomAsciiOfLength(5))
.put("shield.ssl.truststore.algorithm", "_algorithm")
.put("xpack.security.ssl.keystore.path", "/path/to/keystore")
.put("xpack.security.ssl.ciphers", "_ciphers")
.put("xpack.security.ssl.supported_protocols", randomFrom(SSLSettings.Globals.DEFAULT_SUPPORTED_PROTOCOLS))
.put("xpack.security.ssl.keystore.password", randomAsciiOfLength(5))
.put("xpack.security.ssl.keystore.algorithm", "_algorithm")
.put("xpack.security.ssl.keystore.key_password", randomAsciiOfLength(5))
.put("xpack.security.ssl.truststore.password", randomAsciiOfLength(5))
.put("xpack.security.ssl.truststore.algorithm", "_algorithm")
// client profile
.put("transport.profiles.client.port", clientProfilePort + "-" + (clientProfilePort + 100))
.put("transport.profiles.client.shield.keystore.path", "/path/to/keystore")
.put("transport.profiles.client.shield.ciphers", "_ciphers")
.put("transport.profiles.client.shield.supported_protocols", randomFrom(AbstractSSLService.DEFAULT_SUPPORTED_PROTOCOLS))
.put("transport.profiles.client.shield.keystore.password", randomAsciiOfLength(5))
.put("transport.profiles.client.shield.keystore.algorithm", "_algorithm")
.put("transport.profiles.client.shield.keystore.key_password", randomAsciiOfLength(5))
.put("transport.profiles.client.shield.truststore.password", randomAsciiOfLength(5))
.put("transport.profiles.client.shield.truststore.algorithm", "_algorithm")
.put("transport.profiles.client.xpack.security.keystore.path", "/path/to/keystore")
.put("transport.profiles.client.xpack.security.ciphers", "_ciphers")
.put("transport.profiles.client.xpack.security.supported_protocols",
randomFrom(SSLSettings.Globals.DEFAULT_SUPPORTED_PROTOCOLS))
.put("transport.profiles.client.xpack.security.keystore.password", randomAsciiOfLength(5))
.put("transport.profiles.client.xpack.security.keystore.algorithm", "_algorithm")
.put("transport.profiles.client.xpack.security.keystore.key_password", randomAsciiOfLength(5))
.put("transport.profiles.client.xpack.security.truststore.password", randomAsciiOfLength(5))
.put("transport.profiles.client.xpack.security.truststore.algorithm", "_algorithm")
// custom settings
.put("foo.bar", "_secret")
.put("foo.baz", "_secret")
.put("bar.baz", "_secret")
.put("baz.foo", "_not_a_secret") // should not be filtered
.put("shield.hide_settings", "foo.*,bar.baz")
.put("xpack.security.hide_settings", "foo.*,bar.baz")
.build();
}
@ -147,40 +150,40 @@ public class SettingsFilterTests extends ShieldIntegTestCase {
List<Settings> list = extractSettings(response.getBody());
for (Settings settings : list) {
assertThat(settings.get("shield.authc.realms.ldap1.hostname_verification"), nullValue());
assertThat(settings.get("shield.authc.realms.ldap1.bind_password"), nullValue());
assertThat(settings.get("shield.authc.realms.ldap1.bind_dn"), nullValue());
assertThat(settings.get("shield.authc.realms.ldap1.url"), is("ldap://host.domain"));
assertThat(settings.get("xpack.security.authc.realms.ldap1.hostname_verification"), nullValue());
assertThat(settings.get("xpack.security.authc.realms.ldap1.bind_password"), nullValue());
assertThat(settings.get("xpack.security.authc.realms.ldap1.bind_dn"), nullValue());
assertThat(settings.get("xpack.security.authc.realms.ldap1.url"), is("ldap://host.domain"));
assertThat(settings.get("shield.authc.realms.ad1.hostname_verification"), nullValue());
assertThat(settings.get("shield.authc.realms.ad1.url"), is("ldap://host.domain"));
assertThat(settings.get("xpack.security.authc.realms.ad1.hostname_verification"), nullValue());
assertThat(settings.get("xpack.security.authc.realms.ad1.url"), is("ldap://host.domain"));
assertThat(settings.get("shield.authc.realms.pki1.truststore.path"), nullValue());
assertThat(settings.get("shield.authc.realms.pki1.truststore.password"), nullValue());
assertThat(settings.get("shield.authc.realms.pki1.truststore.algorithm"), nullValue());
assertThat(settings.get("shield.authc.realms.pki1.type"), is("pki"));
assertThat(settings.get("xpack.security.authc.realms.pki1.truststore.path"), nullValue());
assertThat(settings.get("xpack.security.authc.realms.pki1.truststore.password"), nullValue());
assertThat(settings.get("xpack.security.authc.realms.pki1.truststore.algorithm"), nullValue());
assertThat(settings.get("xpack.security.authc.realms.pki1.type"), is("pki"));
assertThat(settings.get("shield.ssl.keystore.path"), nullValue());
assertThat(settings.get("shield.ssl.ciphers"), nullValue());
assertThat(settings.get("shield.ssl.supported_protocols"), nullValue());
assertThat(settings.get("shield.ssl.keystore.password"), nullValue());
assertThat(settings.get("shield.ssl.keystore.algorithm"), nullValue());
assertThat(settings.get("shield.ssl.keystore.key_password"), nullValue());
assertThat(settings.get("shield.ssl.truststore.password"), nullValue());
assertThat(settings.get("shield.ssl.truststore.algorithm"), nullValue());
assertThat(settings.get("xpack.security.ssl.keystore.path"), nullValue());
assertThat(settings.get("xpack.security.ssl.ciphers"), nullValue());
assertThat(settings.get("xpack.security.ssl.supported_protocols"), nullValue());
assertThat(settings.get("xpack.security.ssl.keystore.password"), nullValue());
assertThat(settings.get("xpack.security.ssl.keystore.algorithm"), nullValue());
assertThat(settings.get("xpack.security.ssl.keystore.key_password"), nullValue());
assertThat(settings.get("xpack.security.ssl.truststore.password"), nullValue());
assertThat(settings.get("xpack.security.ssl.truststore.algorithm"), nullValue());
// the client profile settings is also filtered out
assertThat(settings.get("transport.profiles.client.port"), notNullValue());
assertThat(settings.get("transport.profiles.client.shield.keystore.path"), nullValue());
assertThat(settings.get("transport.profiles.client.shield.ciphers"), nullValue());
assertThat(settings.get("transport.profiles.client.shield.supported_protocols"), nullValue());
assertThat(settings.get("transport.profiles.client.shield.keystore.password"), nullValue());
assertThat(settings.get("transport.profiles.client.shield.keystore.algorithm"), nullValue());
assertThat(settings.get("transport.profiles.client.shield.keystore.key_password"), nullValue());
assertThat(settings.get("transport.profiles.client.shield.truststore.password"), nullValue());
assertThat(settings.get("transport.profiles.client.shield.truststore.algorithm"), nullValue());
assertThat(settings.get("transport.profiles.client.xpack.security.keystore.path"), nullValue());
assertThat(settings.get("transport.profiles.client.xpack.security.ciphers"), nullValue());
assertThat(settings.get("transport.profiles.client.xpack.security.supported_protocols"), nullValue());
assertThat(settings.get("transport.profiles.client.xpack.security.keystore.password"), nullValue());
assertThat(settings.get("transport.profiles.client.xpack.security.keystore.algorithm"), nullValue());
assertThat(settings.get("transport.profiles.client.xpack.security.keystore.key_password"), nullValue());
assertThat(settings.get("transport.profiles.client.xpack.security.truststore.password"), nullValue());
assertThat(settings.get("transport.profiles.client.xpack.security.truststore.algorithm"), nullValue());
assertThat(settings.get("shield.hide_settings"), nullValue());
assertThat(settings.get("xpack.security.hide_settings"), nullValue());
assertThat(settings.get("foo.bar"), nullValue());
assertThat(settings.get("foo.baz"), nullValue());
assertThat(settings.get("bar.baz"), nullValue());

View File

@ -12,6 +12,7 @@ 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.shield.Security;
import org.elasticsearch.shield.authc.support.Hasher;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.test.ShieldIntegTestCase;
@ -90,7 +91,7 @@ public class ShieldClearScrollTests extends ShieldIntegTestCase {
String shieldUser = "allowed_user:change_me";
String basicAuth = basicAuthHeaderValue("allowed_user", new SecuredString("change_me".toCharArray()));
Map<String, String> headers = new HashMap<>();
headers.put("shield.user", shieldUser);
headers.put(Security.USER_SETTING.getKey(), shieldUser);
headers.put(BASIC_AUTH_HEADER, basicAuth);
ClearScrollResponse clearScrollResponse = internalCluster().transportClient().filterWithHeader(headers)
.prepareClearScroll()
@ -104,7 +105,7 @@ public class ShieldClearScrollTests extends ShieldIntegTestCase {
String shieldUser = "denied_user:change_me";
String basicAuth = basicAuthHeaderValue("denied_user", new SecuredString("change_me".toCharArray()));
Map<String, String> headers = new HashMap<>();
headers.put("shield.user", shieldUser);
headers.put(Security.USER_SETTING.getKey(), shieldUser);
headers.put(BASIC_AUTH_HEADER, basicAuth);
assertThrows(internalCluster().transportClient().filterWithHeader(headers)
.prepareClearScroll()

View File

@ -42,7 +42,7 @@ import static org.hamcrest.Matchers.is;
*/
abstract public class AbstractAdLdapRealmTestCase extends ShieldIntegTestCase {
public static final String SHIELD_AUTHC_REALMS_EXTERNAL = "shield.authc.realms.external";
public static final String SHIELD_AUTHC_REALMS_EXTERNAL = "xpack.security.authc.realms.external";
public static final String PASSWORD = "NickFuryHeartsES";
public static final String ASGARDIAN_INDEX = "gods";
public static final String PHILANTHROPISTS_INDEX = "philanthropists";
@ -161,11 +161,11 @@ abstract public class AbstractAdLdapRealmTestCase extends ShieldIntegTestCase {
}
return settingsBuilder()
.put("shield.ssl.keystore.path", store)
.put("shield.ssl.keystore.password", password)
.put(ShieldNettyTransport.HOSTNAME_VERIFICATION_SETTING, false)
.put("shield.ssl.truststore.path", store)
.put("shield.ssl.truststore.password", password).build();
.put("xpack.security.ssl.keystore.path", store)
.put("xpack.security.ssl.keystore.password", password)
.put(ShieldNettyTransport.HOSTNAME_VERIFICATION_SETTING.getKey(), false)
.put("xpack.security.ssl.truststore.path", store)
.put("xpack.security.ssl.truststore.password", password).build();
}
/**

View File

@ -13,7 +13,7 @@ import java.io.IOException;
* This tests the group to role mappings from LDAP sources provided by the super class - available from super.realmConfig.
* The super class will provide appropriate group mappings via configGroupMappings()
*/
//@Network
@Network
public class GroupMappingTests extends AbstractAdLdapRealmTestCase {
public void testAuthcAuthz() throws IOException {
String avenger = realmConfig.loginWithCommonName ? "Natasha Romanoff" : "blackwidow";

View File

@ -7,6 +7,7 @@ package org.elasticsearch.shield;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.shield.audit.AuditTrailModule;
import org.elasticsearch.shield.audit.index.IndexAuditTrail;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.XPackPlugin;
@ -19,18 +20,18 @@ import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.not;
public class ShieldPluginSettingsTests extends ESTestCase {
public class SecuritySettingsTests extends ESTestCase {
private static final String TRIBE_T1_SHIELD_ENABLED = "tribe.t1." + XPackPlugin.featureEnabledSetting(Shield.NAME);
private static final String TRIBE_T2_SHIELD_ENABLED = "tribe.t2." + XPackPlugin.featureEnabledSetting(Shield.NAME);
private static final String TRIBE_T1_SHIELD_ENABLED = "tribe.t1." + Security.enabledSetting();
private static final String TRIBE_T2_SHIELD_ENABLED = "tribe.t2." + Security.enabledSetting();
public void testShieldIsMandatoryOnTribes() {
Settings settings = Settings.builder().put("tribe.t1.cluster.name", "non_existing")
.put("tribe.t2.cluster.name", "non_existing").build();
Shield shield = new Shield(settings);
Security security = new Security(settings);
Settings additionalSettings = shield.additionalSettings();
Settings additionalSettings = security.additionalSettings();
assertThat(additionalSettings.getAsArray("tribe.t1.plugin.mandatory", null), arrayContaining(XPackPlugin.NAME));
@ -41,11 +42,11 @@ public class ShieldPluginSettingsTests extends ESTestCase {
Settings settings = Settings.builder().put("tribe.t1.cluster.name", "non_existing")
.putArray("tribe.t1.plugin.mandatory", "test_plugin").build();
Shield shield = new Shield(settings);
Security security = new Security(settings);
//simulate what PluginsService#updatedSettings does to make sure we don't override existing mandatory plugins
try {
Settings.builder().put(settings).put(shield.additionalSettings()).build();
Settings.builder().put(settings).put(security.additionalSettings()).build();
fail("shield cannot change the value of a setting that is already defined, so a exception should be thrown");
} catch (IllegalStateException e) {
assertThat(e.getMessage(), containsString(XPackPlugin.NAME));
@ -57,10 +58,10 @@ public class ShieldPluginSettingsTests extends ESTestCase {
Settings settings = Settings.builder().put("tribe.t1.cluster.name", "non_existing")
.putArray("tribe.t1.plugin.mandatory", "test_plugin", XPackPlugin.NAME).build();
Shield shield = new Shield(settings);
Security security = new Security(settings);
//simulate what PluginsService#updatedSettings does to make sure we don't override existing mandatory plugins
Settings finalSettings = Settings.builder().put(settings).put(shield.additionalSettings()).build();
Settings finalSettings = Settings.builder().put(settings).put(security.additionalSettings()).build();
String[] finalMandatoryPlugins = finalSettings.getAsArray("tribe.t1.plugin.mandatory", null);
assertThat(finalMandatoryPlugins, notNullValue());
@ -73,9 +74,9 @@ public class ShieldPluginSettingsTests extends ESTestCase {
Settings settings = Settings.builder().put("tribe.t1.cluster.name", "non_existing")
.put("tribe.t2.cluster.name", "non_existing").build();
Shield shield = new Shield(settings);
Security security = new Security(settings);
Settings additionalSettings = shield.additionalSettings();
Settings additionalSettings = security.additionalSettings();
assertThat(additionalSettings.getAsBoolean(TRIBE_T1_SHIELD_ENABLED, null), equalTo(true));
assertThat(additionalSettings.getAsBoolean(TRIBE_T2_SHIELD_ENABLED, null), equalTo(true));
@ -86,10 +87,10 @@ public class ShieldPluginSettingsTests extends ESTestCase {
.put(TRIBE_T1_SHIELD_ENABLED, false)
.put("tribe.t2.cluster.name", "non_existing").build();
Shield shield = new Shield(settings);
Security security = new Security(settings);
try {
shield.additionalSettings();
security.additionalSettings();
fail("shield cannot change the value of a setting that is already defined, so a exception should be thrown");
} catch (IllegalStateException e) {
assertThat(e.getMessage(), containsString(TRIBE_T1_SHIELD_ENABLED));
@ -102,10 +103,10 @@ public class ShieldPluginSettingsTests extends ESTestCase {
.put("tribe.t2.cluster.name", "non_existing")
.putArray("tribe.t1.plugin.mandatory", "test_plugin", XPackPlugin.NAME).build();
Shield shield = new Shield(settings);
Security security = new Security(settings);
try {
shield.additionalSettings();
security.additionalSettings();
fail("shield cannot change the value of a setting that is already defined, so a exception should be thrown");
} catch (IllegalStateException e) {
assertThat(e.getMessage(), containsString(TRIBE_T1_SHIELD_ENABLED));
@ -116,43 +117,43 @@ public class ShieldPluginSettingsTests extends ESTestCase {
Settings settings = Settings.builder()
.put("tribe.t1.cluster.name", "non_existing")
.put("tribe.t2.cluster.name", "non_existing")
.put("shield.foo", "bar")
.put("shield.bar", "foo")
.putArray("shield.something.else.here", new String[] { "foo", "bar" })
.put("xpack.security.foo", "bar")
.put("xpack.security.bar", "foo")
.putArray("xpack.security.something.else.here", new String[] { "foo", "bar" })
.build();
Shield shield = new Shield(settings);
Settings additionalSettings = shield.additionalSettings();
Security security = new Security(settings);
Settings additionalSettings = security.additionalSettings();
assertThat(additionalSettings.get("shield.foo"), nullValue());
assertThat(additionalSettings.get("shield.bar"), nullValue());
assertThat(additionalSettings.getAsArray("shield.something.else.here"), is(Strings.EMPTY_ARRAY));
assertThat(additionalSettings.get("tribe.t1.shield.foo"), is("bar"));
assertThat(additionalSettings.get("tribe.t1.shield.bar"), is("foo"));
assertThat(additionalSettings.getAsArray("tribe.t1.shield.something.else.here"), arrayContaining("foo", "bar"));
assertThat(additionalSettings.get("tribe.t2.shield.foo"), is("bar"));
assertThat(additionalSettings.get("tribe.t2.shield.bar"), is("foo"));
assertThat(additionalSettings.getAsArray("tribe.t2.shield.something.else.here"), arrayContaining("foo", "bar"));
assertThat(additionalSettings.get("xpack.security.foo"), nullValue());
assertThat(additionalSettings.get("xpack.security.bar"), nullValue());
assertThat(additionalSettings.getAsArray("xpack.security.something.else.here"), is(Strings.EMPTY_ARRAY));
assertThat(additionalSettings.get("tribe.t1.xpack.security.foo"), is("bar"));
assertThat(additionalSettings.get("tribe.t1.xpack.security.bar"), is("foo"));
assertThat(additionalSettings.getAsArray("tribe.t1.xpack.security.something.else.here"), arrayContaining("foo", "bar"));
assertThat(additionalSettings.get("tribe.t2.xpack.security.foo"), is("bar"));
assertThat(additionalSettings.get("tribe.t2.xpack.security.bar"), is("foo"));
assertThat(additionalSettings.getAsArray("tribe.t2.xpack.security.something.else.here"), arrayContaining("foo", "bar"));
}
public void testValidAutoCreateIndex() {
Shield.validateAutoCreateIndex(Settings.EMPTY);
Shield.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", true).build());
Security.validateAutoCreateIndex(Settings.EMPTY);
Security.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", true).build());
try {
Shield.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", false).build());
Security.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", false).build());
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString(ShieldTemplateService.SECURITY_INDEX_NAME));
assertThat(e.getMessage(), not(containsString(IndexAuditTrail.INDEX_NAME_PREFIX)));
}
Shield.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", ".security").build());
Shield.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", "*s*").build());
Shield.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", ".s*").build());
Security.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", ".security").build());
Security.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", "*s*").build());
Security.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", ".s*").build());
try {
Shield.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", "foo").build());
Security.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", "foo").build());
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString(ShieldTemplateService.SECURITY_INDEX_NAME));
@ -160,22 +161,22 @@ public class ShieldPluginSettingsTests extends ESTestCase {
}
try {
Shield.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", ".shield_audit_log*").build());
Security.validateAutoCreateIndex(Settings.builder().put("action.auto_create_index", ".shield_audit_log*").build());
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString(ShieldTemplateService.SECURITY_INDEX_NAME));
}
Shield.validateAutoCreateIndex(Settings.builder()
Security.validateAutoCreateIndex(Settings.builder()
.put("action.auto_create_index", ".security")
.put("shield.audit.enabled", true)
.put(AuditTrailModule.ENABLED_SETTING.getKey(), true)
.build());
try {
Shield.validateAutoCreateIndex(Settings.builder()
Security.validateAutoCreateIndex(Settings.builder()
.put("action.auto_create_index", ".security")
.put("shield.audit.enabled", true)
.put("shield.audit.outputs", randomFrom("index", "logfile,index"))
.put(AuditTrailModule.ENABLED_SETTING.getKey(), true)
.put(AuditTrailModule.OUTPUTS_SETTING.getKey(), randomFrom("index", "logfile,index"))
.build());
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
@ -183,10 +184,10 @@ public class ShieldPluginSettingsTests extends ESTestCase {
assertThat(e.getMessage(), containsString(IndexAuditTrail.INDEX_NAME_PREFIX));
}
Shield.validateAutoCreateIndex(Settings.builder()
Security.validateAutoCreateIndex(Settings.builder()
.put("action.auto_create_index", ".shield_audit_log*,.security")
.put("shield.audit.enabled", true)
.put("shield.audit.outputs", randomFrom("index", "logfile,index"))
.put(AuditTrailModule.ENABLED_SETTING.getKey(), true)
.put(AuditTrailModule.OUTPUTS_SETTING.getKey(), randomFrom("index", "logfile,index"))
.build());
}
}

View File

@ -14,6 +14,7 @@ import org.elasticsearch.node.MockNode;
import org.elasticsearch.node.Node;
import org.elasticsearch.shield.authc.esnative.NativeRealm;
import org.elasticsearch.shield.authc.file.FileRealm;
import org.elasticsearch.shield.authz.store.FileRolesStore;
import org.elasticsearch.shield.test.ShieldTestUtils;
import org.elasticsearch.test.ShieldSettingsSource;
import org.elasticsearch.xpack.XPackPlugin;
@ -50,14 +51,16 @@ public class ShieldF {
}
Path folder = ShieldTestUtils.createFolder(ShieldTestUtils.createFolder(PathUtils.get(homeDir), "config"), "shield");
settings.put("shield.authc.realms.file.type", FileRealm.TYPE);
settings.put("shield.authc.realms.file.order", "0");
settings.put("shield.authc.realms.file.files.users", writeFile(folder, "users", ShieldSettingsSource.CONFIG_STANDARD_USER));
settings.put("shield.authc.realms.file.files.users_roles", writeFile(folder, "users_roles",
settings.put("xpack.security.authc.realms.file.type", FileRealm.TYPE);
settings.put("xpack.security.authc.realms.file.order", "0");
settings.put("xpack.security.authc.realms.file.files.users",
writeFile(folder, "users", ShieldSettingsSource.CONFIG_STANDARD_USER));
settings.put("xpack.security.authc.realms.file.files.users_roles", writeFile(folder, "users_roles",
ShieldSettingsSource.CONFIG_STANDARD_USER_ROLES));
settings.put("shield.authc.realms.esnative.type", NativeRealm.TYPE);
settings.put("shield.authc.realms.esnative.order", "1");
settings.put("shield.authz.store.files.roles", writeFile(folder, "roles.yml", ShieldSettingsSource.CONFIG_ROLE_ALLOW_ALL));
settings.put("xpack.security.authc.realms.esnative.type", NativeRealm.TYPE);
settings.put("xpack.security.authc.realms.esnative.order", "1");
settings.put(FileRolesStore.ROLES_FILE_SETTING.getKey(),
writeFile(folder, "roles.yml", ShieldSettingsSource.CONFIG_ROLE_ALLOW_ALL));
final CountDownLatch latch = new CountDownLatch(1);
final Node node = new MockNode(settings.build(), Version.CURRENT, Arrays.asList(XPackPlugin.class));

View File

@ -66,7 +66,7 @@ public class ShieldPluginEnabledDisabledTests extends ShieldIntegTestCase {
logger.info("******* shield is {}", enabled ? "enabled" : "disabled");
return Settings.settingsBuilder()
.put(super.nodeSettings(nodeOrdinal))
.put(XPackPlugin.featureEnabledSetting(Shield.NAME), enabled)
.put(XPackPlugin.featureEnabledSetting(Security.NAME), enabled)
.put(NetworkModule.HTTP_ENABLED.getKey(), true)
.build();
}
@ -75,7 +75,7 @@ public class ShieldPluginEnabledDisabledTests extends ShieldIntegTestCase {
protected Settings transportClientSettings() {
return Settings.settingsBuilder()
.put(super.transportClientSettings())
.put(XPackPlugin.featureEnabledSetting(Shield.NAME), enabled)
.put(XPackPlugin.featureEnabledSetting(Security.NAME), enabled)
.build();
}

View File

@ -33,10 +33,10 @@ public class AuditTrailModuleTests extends ESTestCase {
public void testEnabled() throws Exception {
Settings settings = Settings.builder()
.put("client.type", "node")
.put("shield.audit.enabled", false)
.put(AuditTrailModule.ENABLED_SETTING.getKey(), false)
.build();
SettingsModule settingsModule = new SettingsModule(settings);
settingsModule.registerSetting(Setting.boolSetting("shield.audit.enabled", true, Setting.Property.NodeScope));
settingsModule.registerSetting(AuditTrailModule.ENABLED_SETTING);
Injector injector = Guice.createInjector(settingsModule, new AuditTrailModule(settings));
AuditTrail auditTrail = injector.getInstance(AuditTrail.class);
assertThat(auditTrail, is(AuditTrail.NOOP));
@ -52,13 +52,13 @@ public class AuditTrailModuleTests extends ESTestCase {
public void testLogfile() throws Exception {
Settings settings = Settings.builder()
.put("shield.audit.enabled", true)
.put(AuditTrailModule.ENABLED_SETTING.getKey(), true)
.put("client.type", "node")
.build();
ThreadPool pool = new ThreadPool("testLogFile");
try {
SettingsModule settingsModule = new SettingsModule(settings);
settingsModule.registerSetting(Setting.boolSetting("shield.audit.enabled", true, Setting.Property.NodeScope));
settingsModule.registerSetting(AuditTrailModule.ENABLED_SETTING);
Injector injector = Guice.createInjector(
settingsModule,
new NetworkModule(new NetworkService(settings), settings, false, new NamedWriteableRegistry()) {
@ -85,13 +85,13 @@ public class AuditTrailModuleTests extends ESTestCase {
public void testUnknownOutput() throws Exception {
Settings settings = Settings.builder()
.put("shield.audit.enabled", true)
.put("shield.audit.outputs" , "foo")
.put(AuditTrailModule.ENABLED_SETTING.getKey(), true)
.put(AuditTrailModule.OUTPUTS_SETTING.getKey() , "foo")
.put("client.type", "node")
.build();
SettingsModule settingsModule = new SettingsModule(settings);
settingsModule.registerSetting(Setting.boolSetting("shield.audit.enabled", true, Setting.Property.NodeScope));
settingsModule.registerSetting(Setting.simpleString("shield.audit.outputs", Setting.Property.NodeScope));
settingsModule.registerSetting(AuditTrailModule.ENABLED_SETTING);
settingsModule.registerSetting(AuditTrailModule.OUTPUTS_SETTING);
try {
Guice.createInjector(settingsModule, new AuditTrailModule(settings));
fail("Expect initialization to fail when an unknown audit trail output is configured");

View File

@ -7,6 +7,7 @@ package org.elasticsearch.shield.audit.index;
import org.elasticsearch.test.ESTestCase;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Locale;
@ -15,7 +16,7 @@ import static org.hamcrest.Matchers.is;
public class IndexAuditLevelTests extends ESTestCase {
public void testAllIndexAuditLevel() {
EnumSet<IndexAuditLevel> enumSet = IndexAuditLevel.parse(new String[] { "_all" });
EnumSet<IndexAuditLevel> enumSet = IndexAuditLevel.parse(Collections.singletonList("_all"));
IndexAuditLevel[] levels = IndexAuditLevel.values();
assertThat(enumSet.size(), is(levels.length));
for (IndexAuditLevel level : levels) {
@ -24,13 +25,13 @@ public class IndexAuditLevelTests extends ESTestCase {
}
public void testExcludeHasPreference() {
EnumSet<IndexAuditLevel> enumSet = IndexAuditLevel.parse(new String[] { "_all" }, new String[] { "_all" });
EnumSet<IndexAuditLevel> enumSet = IndexAuditLevel.parse(Collections.singletonList("_all"), Collections.singletonList("_all"));
assertThat(enumSet.size(), is(0));
}
public void testExcludeHasPreferenceSingle() {
String excluded = randomFrom(IndexAuditLevel.values()).toString().toLowerCase(Locale.ROOT);
EnumSet<IndexAuditLevel> enumSet = IndexAuditLevel.parse(new String[] { "_all" }, new String[] { excluded });
EnumSet<IndexAuditLevel> enumSet = IndexAuditLevel.parse(Collections.singletonList("_all"), Collections.singletonList(excluded));
EnumSet<IndexAuditLevel> expected = EnumSet.allOf(IndexAuditLevel.class);
expected.remove(IndexAuditLevel.valueOf(excluded.toUpperCase(Locale.ROOT)));
assertThat(enumSet, equalTo(expected));

View File

@ -24,11 +24,9 @@ import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.SystemUser;
import org.elasticsearch.shield.User;
import org.elasticsearch.shield.XPackUser;
import org.elasticsearch.shield.authc.AuthenticationService;
import org.elasticsearch.shield.authc.AuthenticationToken;
import org.elasticsearch.shield.transport.filter.IPFilter;
import org.elasticsearch.shield.transport.filter.ShieldIpFilterRule;
@ -100,30 +98,30 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase {
private Settings commonSettings(IndexNameResolver.Rollover rollover) {
return Settings.builder()
.put("shield.audit.enabled", true)
.put("shield.audit.outputs", "index, logfile")
.put("shield.audit.index.bulk_size", 1)
.put("shield.audit.index.flush_interval", "1ms")
.put("shield.audit.index.rollover", rollover.name().toLowerCase(Locale.ENGLISH))
.put("shield.audit.index.settings.index.number_of_shards", numShards)
.put("shield.audit.index.settings.index.number_of_replicas", numReplicas)
.put("xpack.security.audit.enabled", true)
.put("xpack.security.audit.outputs", "index, logfile")
.put("xpack.security.audit.index.bulk_size", 1)
.put("xpack.security.audit.index.flush_interval", "1ms")
.put("xpack.security.audit.index.rollover", rollover.name().toLowerCase(Locale.ENGLISH))
.put("xpack.security.audit.index.settings.index.number_of_shards", numShards)
.put("xpack.security.audit.index.settings.index.number_of_replicas", numReplicas)
.build();
}
private Settings remoteSettings(String address, int port, String clusterName) {
return Settings.builder()
.put("shield.audit.index.client.hosts", address + ":" + port)
.put("shield.audit.index.client.cluster.name", clusterName)
.put("xpack.security.audit.index.client.hosts", address + ":" + port)
.put("xpack.security.audit.index.client.cluster.name", clusterName)
.build();
}
private Settings levelSettings(String[] includes, String[] excludes) {
Settings.Builder builder = Settings.builder();
if (includes != null) {
builder.putArray("shield.audit.index.events.include", includes);
builder.putArray("xpack.security.audit.index.events.include", includes);
}
if (excludes != null) {
builder.putArray("shield.audit.index.events.exclude", excludes);
builder.putArray("xpack.security.audit.index.events.exclude", excludes);
}
return builder.build();
}
@ -148,7 +146,6 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase {
numReplicas = numberOfReplicas();
numShards = numberOfShards();
Settings settings = settings(rollover, includes, excludes);
AuthenticationService authService = mock(AuthenticationService.class);
remoteIndexing = randomBoolean();
if (remoteIndexing) {
@ -166,7 +163,7 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase {
public Settings nodeSettings(int nodeOrdinal) {
Settings.Builder builder = Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(XPackPlugin.featureEnabledSetting(Shield.NAME), useShield);
.put(XPackPlugin.featureEnabledSetting(Security.NAME), useShield);
return builder.build();
}
};
@ -182,34 +179,27 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase {
Settings.Builder builder = Settings.builder()
.put(settings)
.put(XPackPlugin.featureEnabledSetting(Shield.NAME), useShield)
.put(XPackPlugin.featureEnabledSetting(Security.NAME), useShield)
.put(remoteSettings(NetworkAddress.formatAddress(inet.address().getAddress()), inet.address().getPort(), cluster2Name))
.put("shield.audit.index.client.shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD);
.put("xpack.security.audit.index.client." + Security.USER_SETTING.getKey(), DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD);
if (useSSL) {
for (Map.Entry<String, String> entry : cluster2SettingsSource.getClientSSLSettings().getAsMap().entrySet()) {
builder.put("shield.audit.index.client." + entry.getKey(), entry.getValue());
builder.put("xpack.security.audit.index.client." + entry.getKey(), entry.getValue());
}
}
settings = builder.build();
doThrow(new IllegalStateException("indexing user should not be attached when sending remotely"))
.when(authService).attachUserHeaderIfMissing(eq(XPackUser.INSTANCE));
}
settings = Settings.builder().put(settings).put("path.home", createTempDir()).build();
logger.info("--> settings: [{}]", settings.getAsMap().toString());
when(authService.authenticate(mock(RestRequest.class))).thenThrow(new UnsupportedOperationException(""));
when(authService.authenticate("_action", new LocalHostMockMessage(), XPackUser.INSTANCE))
.thenThrow(new UnsupportedOperationException(""));
Transport transport = mock(Transport.class);
BoundTransportAddress boundTransportAddress = new BoundTransportAddress(new TransportAddress[]{DummyTransportAddress.INSTANCE},
DummyTransportAddress.INSTANCE);
when(transport.boundAddress()).thenReturn(boundTransportAddress);
threadPool = new ThreadPool("index audit trail tests");
auditor = new IndexAuditTrail(settings, authService, transport, Providers.of(internalClient()), threadPool,
mock(ClusterService.class));
auditor = new IndexAuditTrail(settings, transport, Providers.of(internalClient()), threadPool, mock(ClusterService.class));
auditor.start(true);
}

View File

@ -12,7 +12,6 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.transport.DummyTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.shield.authc.AuthenticationService;
import org.elasticsearch.test.ShieldIntegTestCase;
import org.elasticsearch.test.rest.FakeRestRequest;
import org.elasticsearch.threadpool.ThreadPool;
@ -46,13 +45,12 @@ public class IndexAuditTrailUpdateMappingTests extends ShieldIntegTestCase {
public void testMappingIsUpdated() throws Exception {
// Setup
IndexNameResolver.Rollover rollover = randomFrom(HOURLY, DAILY, WEEKLY, MONTHLY);
AuthenticationService authService = mock(AuthenticationService.class);
Settings settings = Settings.builder().put("shield.audit.index.rollover", rollover.name().toLowerCase(Locale.ENGLISH))
Settings settings = Settings.builder().put("xpack.security.audit.index.rollover", rollover.name().toLowerCase(Locale.ENGLISH))
.put("path.home", createTempDir()).build();
Transport transport = mock(Transport.class);
when(transport.boundAddress()).thenReturn(new BoundTransportAddress(new TransportAddress[] { DummyTransportAddress.INSTANCE },
DummyTransportAddress.INSTANCE));
auditor = new IndexAuditTrail(settings, authService, transport, Providers.of(internalClient()), threadPool,
auditor = new IndexAuditTrail(settings, transport, Providers.of(internalClient()), threadPool,
mock(ClusterService.class));
// before starting we add an event

View File

@ -54,8 +54,8 @@ public class RemoteIndexAuditTrailStartingTests extends ShieldIntegTestCase {
public Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put("shield.audit.enabled", localAudit)
.put("shield.audit.outputs", outputs)
.put("xpack.security.audit.enabled", localAudit)
.put("xpack.security.audit.outputs", outputs)
.build();
}
@ -92,15 +92,15 @@ public class RemoteIndexAuditTrailStartingTests extends ShieldIntegTestCase {
public Settings nodeSettings(int nodeOrdinal) {
Settings.Builder builder = Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put("shield.audit.enabled", true)
.put("shield.audit.outputs", randomFrom("index", "index,logfile"))
.putArray("shield.audit.index.client.hosts", addresses.toArray(new String[addresses.size()]))
.put("shield.audit.index.client.cluster.name", clusterName)
.put("shield.audit.index.client.shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD);
.put("xpack.security.audit.enabled", true)
.put("xpack.security.audit.outputs", randomFrom("index", "index,logfile"))
.putArray("xpack.security.audit.index.client.hosts", addresses.toArray(new String[addresses.size()]))
.put("xpack.security.audit.index.client.cluster.name", clusterName)
.put("xpack.security.audit.index.client.xpack.security.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD);
if (useSSL) {
for (Map.Entry<String, String> entry : getClientSSLSettings().getAsMap().entrySet()) {
builder.put("shield.audit.index.client." + entry.getKey(), entry.getValue());
builder.put("xpack.security.audit.index.client." + entry.getKey(), entry.getValue());
}
}
return builder.build();

View File

@ -109,9 +109,9 @@ public class LoggingAuditTrailTests extends ESTestCase {
@Before
public void init() throws Exception {
settings = Settings.builder()
.put("shield.audit.logfile.prefix.emit_node_host_address", randomBoolean())
.put("shield.audit.logfile.prefix.emit_node_host_name", randomBoolean())
.put("shield.audit.logfile.prefix.emit_node_name", randomBoolean())
.put("xpack.security.audit.logfile.prefix.emit_node_host_address", randomBoolean())
.put("xpack.security.audit.logfile.prefix.emit_node_host_name", randomBoolean())
.put("xpack.security.audit.logfile.prefix.emit_node_name", randomBoolean())
.build();
transport = mock(Transport.class);
when(transport.lifecycleState()).thenReturn(Lifecycle.State.STARTED);

View File

@ -22,8 +22,8 @@ import static org.hamcrest.Matchers.nullValue;
public class AnonymousUserHolderTests extends ESTestCase {
public void testResolveAnonymousUser() throws Exception {
Settings settings = Settings.builder()
.put("shield.authc.anonymous.username", "anonym1")
.putArray("shield.authc.anonymous.roles", "r1", "r2", "r3")
.put(AnonymousService.USERNAME_SETTING.getKey(), "anonym1")
.putArray(AnonymousService.ROLES_SETTING.getKey(), "r1", "r2", "r3")
.build();
User user = AnonymousService.resolveAnonymousUser(settings);
assertThat(user, notNullValue());
@ -31,7 +31,7 @@ public class AnonymousUserHolderTests extends ESTestCase {
assertThat(user.roles(), arrayContainingInAnyOrder("r1", "r2", "r3"));
settings = Settings.builder()
.putArray("shield.authc.anonymous.roles", "r1", "r2", "r3")
.putArray(AnonymousService.ROLES_SETTING.getKey(), "r1", "r2", "r3")
.build();
user = AnonymousService.resolveAnonymousUser(settings);
assertThat(user, notNullValue());
@ -42,7 +42,7 @@ public class AnonymousUserHolderTests extends ESTestCase {
public void testResolveAnonymousUser_NoSettings() throws Exception {
Settings settings = randomBoolean() ?
Settings.EMPTY :
Settings.builder().put("shield.authc.anonymous.username", "user1").build();
Settings.builder().put(AnonymousService.USERNAME_SETTING.getKey(), "user1").build();
User user = AnonymousService.resolveAnonymousUser(settings);
assertThat(user, nullValue());
}
@ -57,7 +57,7 @@ public class AnonymousUserHolderTests extends ESTestCase {
public void testWhenAnonymousEnabled() throws Exception {
Settings settings = Settings.builder()
.putArray("shield.authc.anonymous.roles", "r1", "r2", "r3")
.putArray(AnonymousService.ROLES_SETTING.getKey(), "r1", "r2", "r3")
.build();
AnonymousService anonymousService = new AnonymousService(settings);
assertThat(anonymousService.enabled(), is(true));
@ -74,8 +74,8 @@ public class AnonymousUserHolderTests extends ESTestCase {
public void testDisablingAuthorizationExceptions() {
Settings settings = Settings.builder()
.putArray("shield.authc.anonymous.roles", "r1", "r2", "r3")
.put(AnonymousService.SETTING_AUTHORIZATION_EXCEPTION_ENABLED, false)
.putArray(AnonymousService.ROLES_SETTING.getKey(), "r1", "r2", "r3")
.put(AnonymousService.SETTING_AUTHORIZATION_EXCEPTION_ENABLED.getKey(), false)
.build();
AnonymousService holder = new AnonymousService(settings);
assertThat(holder.authorizationExceptionsEnabled(), is(false));

View File

@ -35,8 +35,8 @@ public class AnonymousUserTests extends ShieldIntegTestCase {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(NetworkModule.HTTP_ENABLED.getKey(), true)
.put("shield.authc.anonymous.roles", "anonymous")
.put(AnonymousService.SETTING_AUTHORIZATION_EXCEPTION_ENABLED, authorizationExceptionsEnabled)
.put(AnonymousService.ROLES_SETTING.getKey(), "anonymous")
.put(AnonymousService.SETTING_AUTHORIZATION_EXCEPTION_ENABLED.getKey(), authorizationExceptionsEnabled)
.build();
}

View File

@ -378,7 +378,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase {
}
public void testAutheticateTransportContextAndHeaderNoSigning() throws Exception {
Settings settings = Settings.builder().put(InternalAuthenticationService.SETTING_SIGN_USER_HEADER, false).build();
Settings settings = Settings.builder().put(InternalAuthenticationService.SIGN_USER_HEADER.getKey(), false).build();
service = new InternalAuthenticationService(settings, realms, auditTrail, cryptoService, anonymousService,
new DefaultAuthenticationFailureHandler(), threadPool);
@ -472,9 +472,9 @@ public class InternalAuthenticationServiceTests extends ESTestCase {
public void testAnonymousUserRest() throws Exception {
String username = randomBoolean() ? AnonymousService.ANONYMOUS_USERNAME : "user1";
Settings.Builder builder = Settings.builder()
.putArray("shield.authc.anonymous.roles", "r1", "r2", "r3");
.putArray(AnonymousService.ROLES_SETTING.getKey(), "r1", "r2", "r3");
if (username != AnonymousService.ANONYMOUS_USERNAME) {
builder.put("shield.authc.anonymous.username", username);
builder.put(AnonymousService.USERNAME_SETTING.getKey(), username);
}
Settings settings = builder.build();
AnonymousService holder = new AnonymousService(settings);
@ -494,7 +494,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase {
public void testAnonymousUserTransportNoDefaultUser() throws Exception {
Settings settings = Settings.builder()
.putArray("shield.authc.anonymous.roles", "r1", "r2", "r3")
.putArray(AnonymousService.ROLES_SETTING.getKey(), "r1", "r2", "r3")
.build();
service = new InternalAuthenticationService(settings, realms, auditTrail, cryptoService, new AnonymousService(settings),
new DefaultAuthenticationFailureHandler(), threadPool);
@ -509,7 +509,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase {
public void testAnonymousUserTransportWithDefaultUser() throws Exception {
Settings settings = Settings.builder()
.putArray("shield.authc.anonymous.roles", "r1", "r2", "r3")
.putArray(AnonymousService.ROLES_SETTING.getKey(), "r1", "r2", "r3")
.build();
service = new InternalAuthenticationService(settings, realms, auditTrail, cryptoService, new AnonymousService(settings),
new DefaultAuthenticationFailureHandler(), threadPool);

View File

@ -62,8 +62,8 @@ public class RealmsTests extends ESTestCase {
Collections.shuffle(orders, random());
Map<Integer, Integer> orderToIndex = new HashMap<>();
for (int i = 0; i < factories.size() - 2; i++) {
builder.put("shield.authc.realms.realm_" + i + ".type", "type_" + i);
builder.put("shield.authc.realms.realm_" + i + ".order", orders.get(i));
builder.put("xpack.security.authc.realms.realm_" + i + ".type", "type_" + i);
builder.put("xpack.security.authc.realms.realm_" + i + ".order", orders.get(i));
orderToIndex.put(orders.get(i), i);
}
Settings settings = builder.build();
@ -82,10 +82,10 @@ public class RealmsTests extends ESTestCase {
public void testWithSettingsWithMultipleInternalRealmsOfSameType() throws Exception {
Settings settings = Settings.builder()
.put("shield.authc.realms.realm_1.type", FileRealm.TYPE)
.put("shield.authc.realms.realm_1.order", 0)
.put("shield.authc.realms.realm_2.type", FileRealm.TYPE)
.put("shield.authc.realms.realm_2.order", 1)
.put("xpack.security.authc.realms.realm_1.type", FileRealm.TYPE)
.put("xpack.security.authc.realms.realm_1.order", 0)
.put("xpack.security.authc.realms.realm_2.type", FileRealm.TYPE)
.put("xpack.security.authc.realms.realm_2.order", 1)
.put("path.home", createTempDir())
.build();
Environment env = new Environment(settings);
@ -124,8 +124,8 @@ public class RealmsTests extends ESTestCase {
Collections.shuffle(orders, random());
Map<Integer, Integer> orderToIndex = new HashMap<>();
for (int i = 0; i < factories.size() - 2; i++) {
builder.put("shield.authc.realms.realm_" + i + ".type", "type_" + i);
builder.put("shield.authc.realms.realm_" + i + ".order", orders.get(i));
builder.put("xpack.security.authc.realms.realm_" + i + ".type", "type_" + i);
builder.put("xpack.security.authc.realms.realm_" + i + ".order", orders.get(i));
orderToIndex.put(orders.get(i), i);
}
Settings settings = builder.build();
@ -156,10 +156,10 @@ public class RealmsTests extends ESTestCase {
assertThat(factories.get("type_0"), notNullValue());
Settings.Builder builder = Settings.builder()
.put("path.home", createTempDir())
.put("shield.authc.realms.foo.type", "ldap")
.put("shield.authc.realms.foo.order", "0")
.put("shield.authc.realms.custom.type", "type_0")
.put("shield.authc.realms.custom.order", "1");
.put("xpack.security.authc.realms.foo.type", "ldap")
.put("xpack.security.authc.realms.foo.order", "0")
.put("xpack.security.authc.realms.custom.type", "type_0")
.put("xpack.security.authc.realms.custom.order", "1");
Settings settings = builder.build();
Environment env = new Environment(settings);
Realms realms = new Realms(settings, env, factories, shieldLicenseState);
@ -192,10 +192,10 @@ public class RealmsTests extends ESTestCase {
Collections.shuffle(orders, random());
Map<Integer, Integer> orderToIndex = new HashMap<>();
for (int i = 0; i < factories.size() - 2; i++) {
builder.put("shield.authc.realms.realm_" + i + ".type", "type_" + i);
builder.put("shield.authc.realms.realm_" + i + ".order", orders.get(i));
builder.put("xpack.security.authc.realms.realm_" + i + ".type", "type_" + i);
builder.put("xpack.security.authc.realms.realm_" + i + ".order", orders.get(i));
boolean enabled = randomBoolean();
builder.put("shield.authc.realms.realm_" + i + ".enabled", enabled);
builder.put("xpack.security.authc.realms.realm_" + i + ".enabled", enabled);
if (enabled) {
orderToIndex.put(orders.get(i), i);
logger.error("put [{}] -> [{}]", orders.get(i), i);
@ -223,7 +223,7 @@ public class RealmsTests extends ESTestCase {
} else {
assertThat(realm.type(), equalTo("type_" + index));
assertThat(realm.name(), equalTo("realm_" + index));
assertThat(settings.getAsBoolean("shield.authc.realms.realm_" + index + ".enabled", true), equalTo(Boolean.TRUE));
assertThat(settings.getAsBoolean("xpack.security.authc.realms.realm_" + index + ".enabled", true), equalTo(Boolean.TRUE));
count++;
}
}

View File

@ -13,6 +13,7 @@ import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.shield.authc.support.SecuredStringTests;
import org.elasticsearch.shield.authc.support.UsernamePasswordToken;
@ -73,8 +74,8 @@ public class RunAsIntegTests extends ShieldIntegTestCase {
}
public void testUserImpersonation() throws Exception {
try (TransportClient client = getTransportClient(
Settings.builder().put("shield.user", TRANSPORT_CLIENT_USER + ":" + ShieldSettingsSource.DEFAULT_PASSWORD).build())) {
try (TransportClient client = getTransportClient(Settings.builder()
.put(Security.USER_SETTING.getKey(), TRANSPORT_CLIENT_USER + ":" + ShieldSettingsSource.DEFAULT_PASSWORD).build())) {
//ensure the client can connect
awaitBusy(() -> {
return client.connectedNodes().size() > 0;
@ -139,8 +140,8 @@ public class RunAsIntegTests extends ShieldIntegTestCase {
}
public void testEmptyUserImpersonationHeader() throws Exception {
try (TransportClient client = getTransportClient(Settings.builder().put("shield.user", TRANSPORT_CLIENT_USER + ":" +
ShieldSettingsSource.DEFAULT_PASSWORD).build())) {
try (TransportClient client = getTransportClient(Settings.builder()
.put(Security.USER_SETTING.getKey(), TRANSPORT_CLIENT_USER + ":" + ShieldSettingsSource.DEFAULT_PASSWORD).build())) {
//ensure the client can connect
awaitBusy(() -> {
return client.connectedNodes().size() > 0;
@ -171,8 +172,8 @@ public class RunAsIntegTests extends ShieldIntegTestCase {
}
public void testNonExistentRunAsUser() throws Exception {
try (TransportClient client = getTransportClient(Settings.builder().put("shield.user", TRANSPORT_CLIENT_USER + ":" +
ShieldSettingsSource.DEFAULT_PASSWORD).build())) {
try (TransportClient client = getTransportClient(Settings.builder()
.put(Security.USER_SETTING.getKey(), TRANSPORT_CLIENT_USER + ":" + ShieldSettingsSource.DEFAULT_PASSWORD).build())) {
//ensure the client can connect
awaitBusy(() -> {
return client.connectedNodes().size() > 0;

View File

@ -42,8 +42,8 @@ public class ActiveDirectoryGroupsResolverTests extends ESTestCase {
Path keystore = getDataPath("../ldap/support/ldaptrust.jks");
Environment env = new Environment(Settings.builder().put("path.home", createTempDir()).build());
ClientSSLService clientSSLService = new ClientSSLService(Settings.builder()
.put("shield.ssl.keystore.path", keystore)
.put("shield.ssl.keystore.password", "changeit")
.put("xpack.security.ssl.keystore.path", keystore)
.put("xpack.security.ssl.keystore.password", "changeit")
.build());
clientSSLService.setEnvironment(env);

View File

@ -50,8 +50,8 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase {
* verification tests since a re-established connection does not perform hostname verification.
*/
clientSSLService = new ClientSSLService(Settings.builder()
.put("shield.ssl.keystore.path", keystore)
.put("shield.ssl.keystore.password", "changeit")
.put("xpack.security.ssl.keystore.path", keystore)
.put("xpack.security.ssl.keystore.password", "changeit")
.build());
clientSSLService.setEnvironment(env);
globalSettings = Settings.builder().put("path.home", createTempDir()).build();

View File

@ -77,11 +77,11 @@ public class FileUserPasswdStoreTests extends ESTestCase {
// writing in utf_16 should cause a parsing error as we try to read the file in utf_8
Files.write(file, Collections.singletonList("aldlfkjldjdflkjd"), StandardCharsets.UTF_16);
Settings esusersSettings = Settings.builder()
Settings fileSettings = Settings.builder()
.put("files.users", file.toAbsolutePath())
.build();
RealmConfig config = new RealmConfig("file-test", esusersSettings, settings, env);
RealmConfig config = new RealmConfig("file-test", fileSettings, settings, env);
ResourceWatcherService watcherService = new ResourceWatcherService(settings, threadPool);
FileUserPasswdStore store = new FileUserPasswdStore(config, watcherService);
assertThat(store.usersCount(), is(0));
@ -92,12 +92,12 @@ public class FileUserPasswdStoreTests extends ESTestCase {
Path tmp = createTempFile();
Files.copy(users, tmp, StandardCopyOption.REPLACE_EXISTING);
Settings esusersSettings = Settings.builder()
Settings fileSettings = Settings.builder()
.put("files.users", tmp.toAbsolutePath())
.build();
RealmConfig config = new RealmConfig("file-test", esusersSettings, settings, env);
RealmConfig config = new RealmConfig("file-test", fileSettings, settings, env);
ResourceWatcherService watcherService = new ResourceWatcherService(settings, threadPool);
final CountDownLatch latch = new CountDownLatch(1);
@ -131,12 +131,12 @@ public class FileUserPasswdStoreTests extends ESTestCase {
Path tmp = createTempFile();
Files.copy(users, tmp, StandardCopyOption.REPLACE_EXISTING);
Settings esusersSettings = Settings.builder()
Settings fileSettings = Settings.builder()
.put("files.users", tmp.toAbsolutePath())
.build();
RealmConfig config = new RealmConfig("file-test", esusersSettings, settings, env);
RealmConfig config = new RealmConfig("file-test", fileSettings, settings, env);
ResourceWatcherService watcherService = new ResourceWatcherService(settings, threadPool);
final CountDownLatch latch = new CountDownLatch(1);

View File

@ -79,11 +79,11 @@ public class FileUserRolesStoreTests extends ESTestCase {
// writing in utf_16 should cause a parsing error as we try to read the file in utf_8
Files.write(file, lines, StandardCharsets.UTF_16);
Settings esusersSettings = Settings.builder()
Settings fileSettings = Settings.builder()
.put("files.users_roles", file.toAbsolutePath())
.build();
RealmConfig config = new RealmConfig("file-test", esusersSettings, settings, env);
RealmConfig config = new RealmConfig("file-test", fileSettings, settings, env);
ResourceWatcherService watcherService = new ResourceWatcherService(settings, threadPool);
FileUserRolesStore store = new FileUserRolesStore(config, watcherService);
assertThat(store.entriesCount(), is(0));
@ -94,11 +94,11 @@ public class FileUserRolesStoreTests extends ESTestCase {
Path tmp = createTempFile();
Files.copy(users, tmp, StandardCopyOption.REPLACE_EXISTING);
Settings esusersSettings = Settings.builder()
Settings fileSettings = Settings.builder()
.put("files.users_roles", tmp.toAbsolutePath())
.build();
RealmConfig config = new RealmConfig("file-test", esusersSettings, settings, env);
RealmConfig config = new RealmConfig("file-test", fileSettings, settings, env);
ResourceWatcherService watcherService = new ResourceWatcherService(settings, threadPool);
final CountDownLatch latch = new CountDownLatch(1);
@ -137,11 +137,11 @@ public class FileUserRolesStoreTests extends ESTestCase {
Path tmp = createTempFile();
Files.copy(users, tmp, StandardCopyOption.REPLACE_EXISTING);
Settings esusersSettings = Settings.builder()
Settings fileSettings = Settings.builder()
.put("files.users_roles", tmp.toAbsolutePath())
.build();
RealmConfig config = new RealmConfig("file-test", esusersSettings, settings, env);
RealmConfig config = new RealmConfig("file-test", fileSettings, settings, env);
ResourceWatcherService watcherService = new ResourceWatcherService(settings, threadPool);
final CountDownLatch latch = new CountDownLatch(1);
@ -232,12 +232,12 @@ public class FileUserRolesStoreTests extends ESTestCase {
.put("path.home", createTempDir())
.build();
Settings esusersSettings = Settings.builder()
Settings fileSettings = Settings.builder()
.put("files.users_roles", usersRoles.toAbsolutePath())
.build();
Environment env = new Environment(settings);
RealmConfig config = new RealmConfig("file-test", esusersSettings, settings, env);
RealmConfig config = new RealmConfig("file-test", fileSettings, settings, env);
ResourceWatcherService watcherService = new ResourceWatcherService(settings, threadPool);
FileUserRolesStore store = new FileUserRolesStore(config, watcherService);
assertThat(store.roles("user"), equalTo(Strings.EMPTY_ARRAY));

View File

@ -78,7 +78,7 @@ public class UsersToolTests extends CommandTestCase {
), StandardCharsets.UTF_8);
settingsBuilder = Settings.builder()
.put("path.home", homeDir)
.put("shield.authc.realms.file.type", "file");
.put("xpack.security.authc.realms.file.type", "file");
}
@AfterClass

View File

@ -72,8 +72,8 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase {
* verification tests since a re-established connection does not perform hostname verification.
*/
clientSSLService = new ClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", keystore)
.put("shield.ssl.keystore.password", "changeit")
.put("xpack.security.ssl.keystore.path", keystore)
.put("xpack.security.ssl.keystore.password", "changeit")
.build());
clientSSLService.setEnvironment(env);
@ -528,7 +528,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase {
Settings.Builder builder = settingsBuilder();
for (Map.Entry<String, String> entry : ldapSettings.getAsMap().entrySet()) {
builder.put("shield.authc.realms.ldap1." + entry.getKey(), entry.getValue());
builder.put("xpack.security.authc.realms.ldap1." + entry.getKey(), entry.getValue());
}
builder.put("path.home", createTempDir());

View File

@ -45,8 +45,8 @@ public class OpenLdapTests extends ESTestCase {
* verification tests since a re-established connection does not perform hostname verification.
*/
clientSSLService = new ClientSSLService(Settings.builder()
.put("shield.ssl.keystore.path", keystore)
.put("shield.ssl.keystore.password", "changeit")
.put("xpack.security.ssl.keystore.path", keystore)
.put("xpack.security.ssl.keystore.password", "changeit")
.build());
clientSSLService.setEnvironment(env);
globalSettings = Settings.builder().put("path.home", createTempDir()).build();

View File

@ -43,8 +43,8 @@ public class SearchGroupsResolverTests extends ESTestCase {
Path keystore = getDataPath("../ldap/support/ldaptrust.jks");
Environment env = new Environment(Settings.builder().put("path.home", createTempDir()).build());
ClientSSLService clientSSLService = new ClientSSLService(Settings.builder()
.put("shield.ssl.keystore.path", keystore)
.put("shield.ssl.keystore.password", "changeit")
.put("xpack.security.ssl.keystore.path", keystore)
.put("xpack.security.ssl.keystore.password", "changeit")
.build());
clientSSLService.setEnvironment(env);

View File

@ -41,8 +41,8 @@ public class UserAttributeGroupsResolverTests extends ESTestCase {
Environment env = new Environment(Settings.builder().put("path.home", createTempDir()).build());
ClientSSLService clientSSLService = new ClientSSLService(Settings.builder()
.put("shield.ssl.keystore.path", keystore)
.put("shield.ssl.keystore.password", "changeit")
.put("xpack.security.ssl.keystore.path", keystore)
.put("xpack.security.ssl.keystore.password", "changeit")
.build());
clientSSLService.setEnvironment(env);

View File

@ -18,6 +18,8 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.http.HttpServerTransport;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.file.FileRealm;
import org.elasticsearch.shield.transport.SSLClientAuth;
import org.elasticsearch.shield.transport.netty.ShieldNettyHttpServerTransport;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
@ -52,16 +54,17 @@ public class PkiAuthenticationTests extends ShieldIntegTestCase {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(NetworkModule.HTTP_ENABLED.getKey(), true)
.put(ShieldNettyHttpServerTransport.HTTP_SSL_SETTING, true)
.put(ShieldNettyHttpServerTransport.HTTP_CLIENT_AUTH_SETTING, sslClientAuth)
.put("shield.authc.realms.file.type", "file")
.put("shield.authc.realms.file.order", "0")
.put("shield.authc.realms.pki1.type", "pki")
.put("shield.authc.realms.pki1.order", "1")
.put("shield.authc.realms.pki1.truststore.path",
.put(ShieldNettyHttpServerTransport.SSL_SETTING.getKey(), true)
.put(ShieldNettyHttpServerTransport.CLIENT_AUTH_SETTING.getKey(), sslClientAuth)
.put("xpack.security.authc.realms.file.type", FileRealm.TYPE)
.put("xpack.security.authc.realms.file.order", "0")
.put("xpack.security.authc.realms.pki1.type", PkiRealm.TYPE)
.put("xpack.security.authc.realms.pki1.order", "1")
.put("xpack.security.authc.realms.pki1.truststore.path",
getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/truststore-testnode-only.jks"))
.put("shield.authc.realms.pki1.truststore.password", "truststore-testnode-only")
.put("shield.authc.realms.pki1.files.role_mapping", getDataPath("role_mapping.yml"))
.put("xpack.security.authc.realms.pki1.truststore.password", "truststore-testnode-only")
.put("xpack.security.authc.realms.pki1.files.role_mapping", getDataPath("role_mapping.yml"))
.build();
}
@ -139,7 +142,7 @@ public class PkiAuthenticationTests extends ShieldIntegTestCase {
.put(transportClientSettings())
.put(additionalSettings)
.put("cluster.name", internalCluster().getClusterName());
builder.remove("shield.user");
builder.remove(Security.USER_SETTING.getKey());
builder.remove("request.headers.Authorization");
return TransportClient.builder().settings(builder).addPlugin(XPackPlugin.class).build();
}

View File

@ -12,10 +12,12 @@ import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.http.HttpServerTransport;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.shield.authc.support.UsernamePasswordToken;
import org.elasticsearch.shield.transport.SSLClientAuth;
import org.elasticsearch.shield.transport.netty.ShieldNettyHttpServerTransport;
import org.elasticsearch.shield.transport.netty.ShieldNettyTransport;
import org.elasticsearch.test.ShieldIntegTestCase;
import org.elasticsearch.test.ShieldSettingsSource;
import org.elasticsearch.test.rest.client.http.HttpRequestBuilder;
@ -54,19 +56,19 @@ public class PkiOptionalClientAuthTests extends ShieldIntegTestCase {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(NetworkModule.HTTP_ENABLED.getKey(), true)
.put(ShieldNettyHttpServerTransport.HTTP_SSL_SETTING, true)
.put(ShieldNettyHttpServerTransport.HTTP_CLIENT_AUTH_SETTING, SSLClientAuth.OPTIONAL)
.put("shield.authc.realms.file.type", "file")
.put("shield.authc.realms.file.order", "0")
.put("shield.authc.realms.pki1.type", "pki")
.put("shield.authc.realms.pki1.order", "1")
.put("shield.authc.realms.pki1.truststore.path",
.put(ShieldNettyHttpServerTransport.SSL_SETTING.getKey(), true)
.put(ShieldNettyHttpServerTransport.CLIENT_AUTH_SETTING.getKey(), SSLClientAuth.OPTIONAL)
.put("xpack.security.authc.realms.file.type", "file")
.put("xpack.security.authc.realms.file.order", "0")
.put("xpack.security.authc.realms.pki1.type", "pki")
.put("xpack.security.authc.realms.pki1.order", "1")
.put("xpack.security.authc.realms.pki1.truststore.path",
getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/truststore-testnode-only.jks"))
.put("shield.authc.realms.pki1.truststore.password", "truststore-testnode-only")
.put("shield.authc.realms.pki1.files.role_mapping", getDataPath("role_mapping.yml"))
.put("xpack.security.authc.realms.pki1.truststore.password", "truststore-testnode-only")
.put("xpack.security.authc.realms.pki1.files.role_mapping", getDataPath("role_mapping.yml"))
.put("transport.profiles.want_client_auth.port", randomClientPortRange)
.put("transport.profiles.want_client_auth.bind_host", "localhost")
.put("transport.profiles.want_client_auth.shield.ssl.client.auth", SSLClientAuth.OPTIONAL)
.put("transport.profiles.want_client_auth.xpack.security.ssl.client.auth", SSLClientAuth.OPTIONAL)
.build();
}
@ -105,9 +107,9 @@ public class PkiOptionalClientAuthTests extends ShieldIntegTestCase {
("/org/elasticsearch/shield/transport/ssl/certs/simple/truststore-testnode-only.jks", "truststore-testnode-only");
Settings settings = Settings.builder()
.put(sslSettingsForStore)
.put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD)
.put(Security.USER_SETTING.getKey(), DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD)
.put("cluster.name", internalCluster().getClusterName())
.put("shield.transport.ssl", true)
.put(ShieldNettyTransport.SSL_SETTING.getKey(), true)
.build();

View File

@ -62,12 +62,12 @@ public class PkiWithoutClientAuthenticationTests extends ShieldIntegTestCase {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(NetworkModule.HTTP_ENABLED.getKey(), true)
.put(ShieldNettyTransport.TRANSPORT_CLIENT_AUTH_SETTING, false)
.put(ShieldNettyHttpServerTransport.HTTP_SSL_SETTING, true)
.put(ShieldNettyHttpServerTransport.HTTP_CLIENT_AUTH_SETTING, randomFrom(SSLClientAuth.NO.name(), false, "false", "FALSE",
SSLClientAuth.NO.name().toLowerCase(Locale.ROOT)))
.put("shield.authc.realms.pki1.type", "pki")
.put("shield.authc.realms.pki1.order", "0")
.put(ShieldNettyTransport.CLIENT_AUTH_SETTING.getKey(), false)
.put(ShieldNettyHttpServerTransport.SSL_SETTING.getKey(), true)
.put(ShieldNettyHttpServerTransport.CLIENT_AUTH_SETTING.getKey(),
randomFrom(SSLClientAuth.NO.name(), false, "false", "FALSE", SSLClientAuth.NO.name().toLowerCase(Locale.ROOT)))
.put("xpack.security.authc.realms.pki1.type", "pki")
.put("xpack.security.authc.realms.pki1.order", "0")
.build();
}

View File

@ -33,8 +33,8 @@ public class PkiWithoutSSLTests extends ShieldIntegTestCase {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(NetworkModule.HTTP_ENABLED.getKey(), true)
.put("shield.authc.realms.pki1.type", "pki")
.put("shield.authc.realms.pki1.order", "0")
.put("xpack.security.authc.realms.pki1.type", "pki")
.put("xpack.security.authc.realms.pki1.order", "0")
.build();
}

View File

@ -342,7 +342,8 @@ public class InternalAuthorizationServiceTests extends ESTestCase {
public void testDenialForAnonymousUser() {
TransportRequest request = new IndicesExistsRequest("b");
ClusterState state = mock(ClusterState.class);
AnonymousService anonymousService = new AnonymousService(Settings.builder().put("shield.authc.anonymous.roles", "a_all").build());
AnonymousService anonymousService =
new AnonymousService(Settings.builder().put(AnonymousService.ROLES_SETTING.getKey(), "a_all").build());
internalAuthorizationService = new InternalAuthorizationService(Settings.EMPTY, rolesStore, clusterService, auditTrail,
anonymousService, new DefaultAuthenticationFailureHandler(), threadPool);
@ -367,8 +368,8 @@ public class InternalAuthorizationServiceTests extends ESTestCase {
TransportRequest request = new IndicesExistsRequest("b");
ClusterState state = mock(ClusterState.class);
AnonymousService anonymousService = new AnonymousService(Settings.builder()
.put("shield.authc.anonymous.roles", "a_all")
.put(AnonymousService.SETTING_AUTHORIZATION_EXCEPTION_ENABLED, false)
.put(AnonymousService.ROLES_SETTING.getKey(), "a_all")
.put(AnonymousService.SETTING_AUTHORIZATION_EXCEPTION_ENABLED.getKey(), false)
.build());
internalAuthorizationService = new InternalAuthorizationService(Settings.EMPTY, rolesStore, clusterService, auditTrail,
anonymousService, new DefaultAuthenticationFailureHandler(), threadPool);

View File

@ -7,7 +7,7 @@ package org.elasticsearch.shield.authz.store;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.shield.Shield;
import org.elasticsearch.shield.Security;
import org.elasticsearch.shield.audit.logfile.CapturingLogger;
import org.elasticsearch.shield.authc.support.RefreshListener;
import org.elasticsearch.shield.authz.permission.ClusterPermission;
@ -54,7 +54,7 @@ public class FileRolesStoreTests extends ESTestCase {
public void testParseFile() throws Exception {
Path path = getDataPath("roles.yml");
Map<String, Role> roles = FileRolesStore.parseFile(path, logger, Settings.builder()
.put(XPackPlugin.featureEnabledSetting(Shield.DLS_FLS_FEATURE), true)
.put(XPackPlugin.featureEnabledSetting(Security.DLS_FLS_FEATURE), true)
.build());
assertThat(roles, notNullValue());
assertThat(roles.size(), is(9));
@ -207,7 +207,7 @@ public class FileRolesStoreTests extends ESTestCase {
Path path = getDataPath("roles.yml");
CapturingLogger logger = new CapturingLogger(CapturingLogger.Level.ERROR);
Map<String, Role> roles = FileRolesStore.parseFile(path, logger, Settings.builder()
.put(XPackPlugin.featureEnabledSetting(Shield.DLS_FLS_FEATURE), false)
.put(XPackPlugin.featureEnabledSetting(Security.DLS_FLS_FEATURE), false)
.build());
assertThat(roles, notNullValue());
assertThat(roles.size(), is(6));
@ -257,7 +257,7 @@ public class FileRolesStoreTests extends ESTestCase {
Settings settings = Settings.builder()
.put("resource.reload.interval.high", "500ms")
.put("shield.authz.store.files.roles", tmp.toAbsolutePath())
.put(FileRolesStore.ROLES_FILE_SETTING.getKey(), tmp.toAbsolutePath())
.put("path.home", createTempDir())
.build();

View File

@ -48,7 +48,7 @@ public class InternalCryptoServiceTests extends ESTestCase {
keyFile = createTempDir().resolve("system_key");
Files.write(keyFile, InternalCryptoService.generateKey());
settings = Settings.builder()
.put("shield.system_key.file", keyFile.toAbsolutePath())
.put(InternalCryptoService.FILE_SETTING.getKey(), keyFile.toAbsolutePath())
.put("resource.reload.interval.high", "2s")
.put("path.home", createTempDir())
.build();

View File

@ -64,7 +64,7 @@ public class SystemKeyToolTests extends CommandTestCase {
Path path = jimfs.getPath(randomAsciiOfLength(10)).resolve("key");
Files.createDirectories(path.getParent());
settingsBuilder.put("shield.system_key.file", path.toAbsolutePath().toString());
settingsBuilder.put(InternalCryptoService.FILE_SETTING.getKey(), path.toAbsolutePath().toString());
execute();
byte[] bytes = Files.readAllBytes(path);
assertEquals(InternalCryptoService.KEY_SIZE / 8, bytes.length);

View File

@ -8,6 +8,7 @@ package org.elasticsearch.shield.rest.action;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.Node;
import org.elasticsearch.shield.authc.AnonymousService;
import org.elasticsearch.shield.authc.support.SecuredString;
import org.elasticsearch.test.ShieldIntegTestCase;
import org.elasticsearch.test.ShieldSettingsSource;
@ -38,9 +39,9 @@ public class RestAuthenticateActionTests extends ShieldIntegTestCase {
.put(NetworkModule.HTTP_ENABLED.getKey(), true);
if (anonymousEnabled) {
builder.put("shield.authc.anonymous.username", "anon")
.putArray("shield.authc.anonymous.roles", ShieldSettingsSource.DEFAULT_ROLE, "foo")
.put("shield.authc.anonymous.authz_exception", false);
builder.put(AnonymousService.USERNAME_SETTING.getKey(), "anon")
.putArray(AnonymousService.ROLES_SETTING.getKey(), ShieldSettingsSource.DEFAULT_ROLE, "foo")
.put(AnonymousService.SETTING_AUTHORIZATION_EXCEPTION_ENABLED.getKey(), false);
}
return builder.build();
}

View File

@ -52,11 +52,11 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testThatInvalidProtocolThrowsException() throws Exception {
try {
new ClientSSLService(settingsBuilder()
.put("shield.ssl.protocol", "non-existing")
.put("shield.ssl.keystore.path", testclientStore)
.put("shield.ssl.keystore.password", "testclient")
.put("shield.ssl.truststore.path", testclientStore)
.put("shield.ssl.truststore.password", "testclient")
.put("xpack.security.ssl.protocol", "non-existing")
.put("xpack.security.ssl.keystore.path", testclientStore)
.put("xpack.security.ssl.keystore.password", "testclient")
.put("xpack.security.ssl.truststore.path", testclientStore)
.put("xpack.security.ssl.truststore.password", "testclient")
.build()).createSSLEngine();
fail("expected an exception");
} catch (ElasticsearchException e) {
@ -68,8 +68,8 @@ public class ClientSSLServiceTests extends ESTestCase {
Path testnodeStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode.jks");
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testclientStore)
.put("shield.ssl.keystore.password", "testclient")
.put("xpack.security.ssl.keystore.path", testclientStore)
.put("xpack.security.ssl.keystore.password", "testclient")
.build());
Settings.Builder settingsBuilder = settingsBuilder()
@ -85,8 +85,8 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testThatSslContextCachingWorks() throws Exception {
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testclientStore)
.put("shield.ssl.keystore.password", "testclient")
.put("xpack.security.ssl.keystore.path", testclientStore)
.put("xpack.security.ssl.keystore.password", "testclient")
.build());
SSLContext sslContext = sslService.sslContext();
@ -98,9 +98,9 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testThatKeyStoreAndKeyCanHaveDifferentPasswords() throws Exception {
Path differentPasswordsStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode-different-passwords.jks");
createClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", differentPasswordsStore)
.put("shield.ssl.keystore.password", "testnode")
.put("shield.ssl.keystore.key_password", "testnode1")
.put("xpack.security.ssl.keystore.path", differentPasswordsStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.keystore.key_password", "testnode1")
.build()).createSSLEngine();
}
@ -108,8 +108,8 @@ public class ClientSSLServiceTests extends ESTestCase {
Path differentPasswordsStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode-different-passwords.jks");
try {
createClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", differentPasswordsStore)
.put("shield.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.keystore.path", differentPasswordsStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.build()).createSSLEngine();
fail("expected an exception");
} catch (ElasticsearchException e) {
@ -119,8 +119,8 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testThatSSLv3IsNotEnabled() throws Exception {
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testclientStore)
.put("shield.ssl.keystore.password", "testclient")
.put("xpack.security.ssl.keystore.path", testclientStore)
.put("xpack.security.ssl.keystore.password", "testclient")
.build());
SSLEngine engine = sslService.createSSLEngine();
assertThat(Arrays.asList(engine.getEnabledProtocols()), not(hasItem("SSLv3")));
@ -128,8 +128,8 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testThatSSLSessionCacheHasDefaultLimits() throws Exception {
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testclientStore)
.put("shield.ssl.keystore.password", "testclient")
.put("xpack.security.ssl.keystore.path", testclientStore)
.put("xpack.security.ssl.keystore.password", "testclient")
.build());
SSLSessionContext context = sslService.sslContext().getServerSessionContext();
assertThat(context.getSessionCacheSize(), equalTo(1000));
@ -138,10 +138,10 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testThatSettingSSLSessionCacheLimitsWorks() throws Exception {
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testclientStore)
.put("shield.ssl.keystore.password", "testclient")
.put("shield.ssl.session.cache_size", "300")
.put("shield.ssl.session.cache_timeout", "600s")
.put("xpack.security.ssl.keystore.path", testclientStore)
.put("xpack.security.ssl.keystore.password", "testclient")
.put("xpack.security.ssl.session.cache_size", "300")
.put("xpack.security.ssl.session.cache_timeout", "600s")
.build());
SSLSessionContext context = sslService.sslContext().getServerSessionContext();
assertThat(context.getSessionCacheSize(), equalTo(300));
@ -156,8 +156,8 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testThatCreateSSLEngineWithOnlyTruststoreWorks() throws Exception {
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.put("shield.ssl.truststore.path", testclientStore)
.put("shield.ssl.truststore.password", "testclient")
.put("xpack.security.ssl.truststore.path", testclientStore)
.put("xpack.security.ssl.truststore.password", "testclient")
.build());
SSLEngine sslEngine = sslService.createSSLEngine();
assertThat(sslEngine, notNullValue());
@ -165,8 +165,8 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testThatCreateSSLEngineWithOnlyKeystoreWorks() throws Exception {
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testclientStore)
.put("shield.ssl.keystore.password", "testclient")
.put("xpack.security.ssl.keystore.path", testclientStore)
.put("xpack.security.ssl.keystore.password", "testclient")
.build());
SSLEngine sslEngine = sslService.createSSLEngine();
assertThat(sslEngine, notNullValue());
@ -187,8 +187,8 @@ public class ClientSSLServiceTests extends ESTestCase {
@Network
public void testThatSSLContextWithKeystoreDoesNotTrustAllPublicCAs() throws Exception {
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testclientStore)
.put("shield.ssl.keystore.password", "testclient")
.put("xpack.security.ssl.keystore.path", testclientStore)
.put("xpack.security.ssl.keystore.password", "testclient")
.build());
SSLContext sslContext = sslService.sslContext();
try (CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext).build()) {
@ -204,7 +204,7 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testThatTruststorePasswordIsRequired() throws Exception {
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.put("shield.ssl.truststore.path", testclientStore)
.put("xpack.security.ssl.truststore.path", testclientStore)
.build());
try {
sslService.sslContext();
@ -216,7 +216,7 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testThatKeystorePasswordIsRequired() throws Exception {
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testclientStore)
.put("xpack.security.ssl.keystore.path", testclientStore)
.build());
try {
sslService.sslContext();
@ -227,11 +227,11 @@ public class ClientSSLServiceTests extends ESTestCase {
}
public void testValidCiphersAndInvalidCiphersWork() throws Exception {
List<String> ciphers = new ArrayList<>(Arrays.asList(AbstractSSLService.DEFAULT_CIPHERS));
List<String> ciphers = new ArrayList<>(SSLSettings.Globals.DEFAULT_CIPHERS);
ciphers.add("foo");
ciphers.add("bar");
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.putArray("shield.ssl.ciphers", ciphers.toArray(new String[ciphers.size()]))
.putArray("xpack.security.ssl.ciphers", ciphers.toArray(new String[ciphers.size()]))
.build());
SSLEngine engine = sslService.createSSLEngine();
assertThat(engine, is(notNullValue()));
@ -241,7 +241,7 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testInvalidCiphersOnlyThrowsException() throws Exception {
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.putArray("shield.ssl.ciphers", new String[] { "foo", "bar" })
.putArray("xpack.security.ssl.ciphers", new String[] { "foo", "bar" })
.build());
try {
sslService.createSSLEngine();
@ -253,8 +253,8 @@ public class ClientSSLServiceTests extends ESTestCase {
public void testThatSSLSocketFactoryHasProperCiphersAndProtocols() throws Exception {
ClientSSLService sslService = createClientSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testclientStore)
.put("shield.ssl.keystore.password", "testclient")
.put("xpack.security.ssl.keystore.path", testclientStore)
.put("xpack.security.ssl.keystore.password", "testclient")
.build());
SSLSocketFactory factory = sslService.sslSocketFactory();
final String[] ciphers = sslService.supportedCiphers(factory.getSupportedCipherSuites(), sslService.ciphers());

View File

@ -7,7 +7,6 @@ package org.elasticsearch.shield.ssl;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.shield.ssl.AbstractSSLService.SSLSettings;
import org.elasticsearch.test.ESTestCase;
import javax.net.ssl.KeyManagerFactory;
@ -22,22 +21,22 @@ import static org.hamcrest.Matchers.nullValue;
public class SSLSettingsTests extends ESTestCase {
public void testThatSSLSettingsWithEmptySettingsHaveCorrectDefaults() {
SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, Settings.EMPTY);
assertThat(sslSettings.keyStorePath, is(nullValue()));
assertThat(sslSettings.keyStorePassword, is(nullValue()));
assertThat(sslSettings.keyPassword, is(nullValue()));
assertThat(sslSettings.keyStorePath, nullValue());
assertThat(sslSettings.keyStorePassword, nullValue());
assertThat(sslSettings.keyPassword, nullValue());
assertThat(sslSettings.keyStoreAlgorithm, is(equalTo(KeyManagerFactory.getDefaultAlgorithm())));
assertThat(sslSettings.sessionCacheSize, is(equalTo(AbstractSSLService.DEFAULT_SESSION_CACHE_SIZE)));
assertThat(sslSettings.sessionCacheTimeout, is(equalTo(AbstractSSLService.DEFAULT_SESSION_CACHE_TIMEOUT)));
assertThat(sslSettings.sslProtocol, is(equalTo(AbstractSSLService.DEFAULT_PROTOCOL)));
assertThat(sslSettings.sessionCacheSize, is(equalTo(SSLSettings.Globals.DEFAULT_SESSION_CACHE_SIZE)));
assertThat(sslSettings.sessionCacheTimeout, is(equalTo(SSLSettings.Globals.DEFAULT_SESSION_CACHE_TIMEOUT)));
assertThat(sslSettings.sslProtocol, is(equalTo(SSLSettings.Globals.DEFAULT_PROTOCOL)));
assertThat(sslSettings.trustStoreAlgorithm, is(equalTo(TrustManagerFactory.getDefaultAlgorithm())));
assertThat(sslSettings.trustStorePassword, is(nullValue()));
assertThat(sslSettings.trustStorePath, is(nullValue()));
assertThat(sslSettings.trustStorePassword, nullValue());
assertThat(sslSettings.trustStorePath, nullValue());
}
public void testThatOnlyKeystoreInSettingsSetsTruststoreSettings() {
Settings settings = settingsBuilder()
.put("shield.ssl.keystore.path", "path")
.put("shield.ssl.keystore.password", "password")
.put("xpack.security.ssl.keystore.path", "path")
.put("xpack.security.ssl.keystore.password", "password")
.build();
// Pass settings in as component settings
SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settings);
@ -60,7 +59,7 @@ public class SSLSettingsTests extends ESTestCase {
public void testThatKeystorePasswordIsDefaultKeyPassword() {
Settings settings = settingsBuilder()
.put("shield.ssl.keystore.password", "password")
.put("xpack.security.ssl.keystore.password", "password")
.build();
// Pass settings in as component settings
SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settings);
@ -76,8 +75,8 @@ public class SSLSettingsTests extends ESTestCase {
public void testThatKeyPasswordCanBeSet() {
Settings settings = settingsBuilder()
.put("shield.ssl.keystore.password", "password")
.put("shield.ssl.keystore.key_password", "key")
.put("xpack.security.ssl.keystore.password", "password")
.put("xpack.security.ssl.keystore.key_password", "key")
.build();
// Pass settings in as component settings
SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settings);
@ -109,16 +108,16 @@ public class SSLSettingsTests extends ESTestCase {
.build();
Settings serviceSettings = settingsBuilder()
.put("shield.ssl.keystore.path", "comp path")
.put("shield.ssl.keystore.password", "comp password")
.put("shield.ssl.keystore.key_password", "comp key")
.put("shield.ssl.keystore.algorithm", "comp algo")
.put("shield.ssl.truststore.path", "comp trust path")
.put("shield.ssl.truststore.password", "comp password for trust")
.put("shield.ssl.truststore.algorithm", "comp trusted")
.put("shield.ssl.protocol", "tls")
.put("shield.ssl.session.cache_size", "7")
.put("shield.ssl.session.cache_timeout", "20m")
.put("xpack.security.ssl.keystore.path", "comp path")
.put("xpack.security.ssl.keystore.password", "comp password")
.put("xpack.security.ssl.keystore.key_password", "comp key")
.put("xpack.security.ssl.keystore.algorithm", "comp algo")
.put("xpack.security.ssl.truststore.path", "comp trust path")
.put("xpack.security.ssl.truststore.password", "comp password for trust")
.put("xpack.security.ssl.truststore.algorithm", "comp trusted")
.put("xpack.security.ssl.protocol", "tls")
.put("xpack.security.ssl.session.cache_size", "7")
.put("xpack.security.ssl.session.cache_timeout", "20m")
.build();
SSLSettings sslSettings = new SSLSettings(profileSettings, serviceSettings);
@ -145,9 +144,9 @@ public class SSLSettingsTests extends ESTestCase {
public void testThatSettingsWithDifferentKeystoresAreNotEqual() {
SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.keystore.path", "path").build());
.put("xpack.security.ssl.keystore.path", "path").build());
SSLSettings sslSettings1 = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.keystore.path", "path1").build());
.put("xpack.security.ssl.keystore.path", "path1").build());
assertThat(sslSettings.equals(sslSettings1), is(equalTo(false)));
assertThat(sslSettings1.equals(sslSettings), is(equalTo(false)));
assertThat(sslSettings.equals(sslSettings), is(equalTo(true)));
@ -156,9 +155,9 @@ public class SSLSettingsTests extends ESTestCase {
public void testThatSettingsWithDifferentProtocolsAreNotEqual() {
SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.protocol", "ssl").build());
.put("xpack.security.ssl.protocol", "ssl").build());
SSLSettings sslSettings1 = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.protocol", "tls").build());
.put("xpack.security.ssl.protocol", "tls").build());
assertThat(sslSettings.equals(sslSettings1), is(equalTo(false)));
assertThat(sslSettings1.equals(sslSettings), is(equalTo(false)));
assertThat(sslSettings.equals(sslSettings), is(equalTo(true)));
@ -167,9 +166,9 @@ public class SSLSettingsTests extends ESTestCase {
public void testThatSettingsWithDifferentTruststoresAreNotEqual() {
SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.truststore.path", "/trust").build());
.put("xpack.security.ssl.truststore.path", "/trust").build());
SSLSettings sslSettings1 = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.truststore.path", "/truststore").build());
.put("xpack.security.ssl.truststore.path", "/truststore").build());
assertThat(sslSettings.equals(sslSettings1), is(equalTo(false)));
assertThat(sslSettings1.equals(sslSettings), is(equalTo(false)));
assertThat(sslSettings.equals(sslSettings), is(equalTo(true)));
@ -184,25 +183,25 @@ public class SSLSettingsTests extends ESTestCase {
public void testThatSettingsWithDifferentKeystoresHaveDifferentHashCode() {
SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.keystore.path", "path").build());
.put("xpack.security.ssl.keystore.path", "path").build());
SSLSettings sslSettings1 = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.keystore.path", "path1").build());
.put("xpack.security.ssl.keystore.path", "path1").build());
assertThat(sslSettings.hashCode(), is(not(equalTo(sslSettings1.hashCode()))));
}
public void testThatSettingsWithDifferentProtocolsHaveDifferentHashCode() {
SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.protocol", "ssl").build());
.put("xpack.security.ssl.protocol", "ssl").build());
SSLSettings sslSettings1 = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.protocol", "tls").build());
.put("xpack.security.ssl.protocol", "tls").build());
assertThat(sslSettings.hashCode(), is(not(equalTo(sslSettings1.hashCode()))));
}
public void testThatSettingsWithDifferentTruststoresHaveDifferentHashCode() {
SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.truststore.path", "/trust").build());
.put("xpack.security.ssl.truststore.path", "/trust").build());
SSLSettings sslSettings1 = new SSLSettings(Settings.EMPTY, settingsBuilder()
.put("shield.ssl.truststore.path", "/truststore").build());
.put("xpack.security.ssl.truststore.path", "/truststore").build());
assertThat(sslSettings.hashCode(), is(not(equalTo(sslSettings1.hashCode()))));
}
}

View File

@ -45,11 +45,11 @@ public class ServerSSLServiceTests extends ESTestCase {
public void testThatInvalidProtocolThrowsException() throws Exception {
Settings settings = settingsBuilder()
.put("shield.ssl.protocol", "non-existing")
.put("shield.ssl.keystore.path", testnodeStore)
.put("shield.ssl.keystore.password", "testnode")
.put("shield.ssl.truststore.path", testnodeStore)
.put("shield.ssl.truststore.password", "testnode")
.put("xpack.security.ssl.protocol", "non-existing")
.put("xpack.security.ssl.keystore.path", testnodeStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.truststore.path", testnodeStore)
.put("xpack.security.ssl.truststore.password", "testnode")
.build();
try {
new ServerSSLService(settings, env).createSSLEngine();
@ -63,8 +63,8 @@ public class ServerSSLServiceTests extends ESTestCase {
Path testClientStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testclient.jks");
Settings settings = settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
.put("shield.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.keystore.path", testnodeStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.build();
ServerSSLService sslService = new ServerSSLService(settings, env);
@ -81,8 +81,8 @@ public class ServerSSLServiceTests extends ESTestCase {
public void testThatSslContextCachingWorks() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
.put("shield.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.keystore.path", testnodeStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.build(), env);
SSLContext sslContext = sslService.sslContext();
@ -94,9 +94,9 @@ public class ServerSSLServiceTests extends ESTestCase {
public void testThatKeyStoreAndKeyCanHaveDifferentPasswords() throws Exception {
Path differentPasswordsStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode-different-passwords.jks");
new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", differentPasswordsStore)
.put("shield.ssl.keystore.password", "testnode")
.put("shield.ssl.keystore.key_password", "testnode1")
.put("xpack.security.ssl.keystore.path", differentPasswordsStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.keystore.key_password", "testnode1")
.build(), env).createSSLEngine();
}
@ -104,8 +104,8 @@ public class ServerSSLServiceTests extends ESTestCase {
Path differentPasswordsStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode-different-passwords.jks");
try {
new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", differentPasswordsStore)
.put("shield.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.keystore.path", differentPasswordsStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.build(), env).createSSLEngine();
fail("expected an exception");
} catch (ElasticsearchException e) {
@ -115,8 +115,8 @@ public class ServerSSLServiceTests extends ESTestCase {
public void testThatSSLv3IsNotEnabled() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
.put("shield.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.keystore.path", testnodeStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.build(), env);
SSLEngine engine = sslService.createSSLEngine();
assertThat(Arrays.asList(engine.getEnabledProtocols()), not(hasItem("SSLv3")));
@ -124,8 +124,8 @@ public class ServerSSLServiceTests extends ESTestCase {
public void testThatSSLSessionCacheHasDefaultLimits() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
.put("shield.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.keystore.path", testnodeStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.build(), env);
SSLSessionContext context = sslService.sslContext().getServerSessionContext();
assertThat(context.getSessionCacheSize(), equalTo(1000));
@ -134,10 +134,10 @@ public class ServerSSLServiceTests extends ESTestCase {
public void testThatSettingSSLSessionCacheLimitsWorks() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
.put("shield.ssl.keystore.password", "testnode")
.put("shield.ssl.session.cache_size", "300")
.put("shield.ssl.session.cache_timeout", "600s")
.put("xpack.security.ssl.keystore.path", testnodeStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.session.cache_size", "300")
.put("xpack.security.ssl.session.cache_timeout", "600s")
.build(), env);
SSLSessionContext context = sslService.sslContext().getServerSessionContext();
assertThat(context.getSessionCacheSize(), equalTo(300));
@ -156,8 +156,8 @@ public class ServerSSLServiceTests extends ESTestCase {
public void testThatCreateSSLEngineWithOnlyTruststoreDoesNotWork() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.truststore.path", testnodeStore)
.put("shield.ssl.truststore.password", "testnode")
.put("xpack.security.ssl.truststore.path", testnodeStore)
.put("xpack.security.ssl.truststore.password", "testnode")
.build(), env);
try {
sslService.createSSLEngine();
@ -169,9 +169,9 @@ public class ServerSSLServiceTests extends ESTestCase {
public void testThatTruststorePasswordIsRequired() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
.put("shield.ssl.keystore.password", "testnode")
.put("shield.ssl.truststore.path", testnodeStore)
.put("xpack.security.ssl.keystore.path", testnodeStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.truststore.path", testnodeStore)
.build(), env);
try {
sslService.sslContext();
@ -183,7 +183,7 @@ public class ServerSSLServiceTests extends ESTestCase {
public void testThatKeystorePasswordIsRequired() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
.put("xpack.security.ssl.keystore.path", testnodeStore)
.build(), env);
try {
sslService.sslContext();
@ -194,13 +194,13 @@ public class ServerSSLServiceTests extends ESTestCase {
}
public void testCiphersAndInvalidCiphersWork() throws Exception {
List<String> ciphers = new ArrayList<>(Arrays.asList(AbstractSSLService.DEFAULT_CIPHERS));
List<String> ciphers = new ArrayList<>(SSLSettings.Globals.DEFAULT_CIPHERS);
ciphers.add("foo");
ciphers.add("bar");
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
.put("shield.ssl.keystore.password", "testnode")
.putArray("shield.ssl.ciphers", ciphers.toArray(new String[ciphers.size()]))
.put("xpack.security.ssl.keystore.path", testnodeStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.putArray("xpack.security.ssl.ciphers", ciphers.toArray(new String[ciphers.size()]))
.build(), env);
SSLEngine engine = sslService.createSSLEngine();
assertThat(engine, is(notNullValue()));
@ -210,9 +210,9 @@ public class ServerSSLServiceTests extends ESTestCase {
public void testInvalidCiphersOnlyThrowsException() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
.put("shield.ssl.keystore.password", "testnode")
.putArray("shield.ssl.ciphers", new String[] { "foo", "bar" })
.put("xpack.security.ssl.keystore.path", testnodeStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.putArray("xpack.security.ssl.ciphers", new String[] { "foo", "bar" })
.build(), env);
try {
sslService.createSSLEngine();
@ -224,8 +224,8 @@ public class ServerSSLServiceTests extends ESTestCase {
public void testThatSSLSocketFactoryHasProperCiphersAndProtocols() throws Exception {
ServerSSLService sslService = new ServerSSLService(settingsBuilder()
.put("shield.ssl.keystore.path", testnodeStore)
.put("shield.ssl.keystore.password", "testnode")
.put("xpack.security.ssl.keystore.path", testnodeStore)
.put("xpack.security.ssl.keystore.password", "testnode")
.build(), env);
SSLSocketFactory factory = sslService.sslSocketFactory();
final String[] ciphers = sslService.supportedCiphers(factory.getSupportedCipherSuites(), sslService.ciphers());

View File

@ -47,13 +47,13 @@ public class ValidationTests extends ESTestCase {
return newArray;
}
public void testESUsersValidateUsername() throws Exception {
public void testUsersValidateUsername() throws Exception {
int length = randomIntBetween(1, 30);
String name = new String(generateValidName(length));
assertThat(Users.validateUsername(name), nullValue());
}
public void testESUsersValidateUsernameInvalidLength() throws Exception {
public void testUsersValidateUsernameInvalidLength() throws Exception {
int length = frequently() ? randomIntBetween(31, 200) : 0; // invalid length
char[] name = new char[length];
if (length > 0) {
@ -62,13 +62,13 @@ public class ValidationTests extends ESTestCase {
assertThat(Users.validateUsername(new String(name)), notNullValue());
}
public void testESUsersValidateUsernameInvalidCharacters() throws Exception {
public void testUsersValidateUsernameInvalidCharacters() throws Exception {
int length = randomIntBetween(1, 30); // valid length
String name = new String(generateInvalidName(length));
assertThat(Users.validateUsername(name), notNullValue());
}
public void testESUsersValidatePassword() throws Exception {
public void testUsersValidatePassword() throws Exception {
String passwd = randomAsciiOfLength(randomIntBetween(0, 20));
logger.info("{}[{}]", passwd, passwd.length());
if (passwd.length() >= 6) {

Some files were not shown because too many files have changed in this diff Show More