Skip to content

Commit

Permalink
[ELY-2112] Automatic registration of client side / JVM wide default S…
Browse files Browse the repository at this point in the history
…SLContext
  • Loading branch information
Skyllarr committed Sep 7, 2021
1 parent ee74e5a commit ff960fd
Show file tree
Hide file tree
Showing 12 changed files with 432 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,15 @@ RuleNode<AuthenticationConfiguration> authRuleMatching(URI uri, String abstractT
RuleNode<SecurityFactory<SSLContext>> sslRuleMatching(URI uri, String abstractType, String abstractTypeAuthority) {
RuleNode<SecurityFactory<SSLContext>> node = this.sslRules;
while (node != null) {
if (node.getRule().matches(uri, abstractType, abstractTypeAuthority)) return node;
node = node.getNext();
if (uri == null) {
if (node.getRule().equals(MatchRule.ALL)) {
return node;
}
node = node.getNext();
} else {
if (node.getRule().matches(uri, abstractType, abstractTypeAuthority)) return node;
node = node.getNext();
}
}
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@ private static AuthenticationConfiguration initializeConfiguration(final URI uri
return configuration;
}

public SSLContext getSSLContext(AuthenticationContext authenticationContext) throws GeneralSecurityException {
return getSSLContext(null, authenticationContext, null, null);
}

/**
* Get the SSL context which matches the given URI, or {@link SSLContext#getDefault()} if there is none.
*
Expand Down Expand Up @@ -230,7 +234,6 @@ public SSLContext getSSLContext(URI uri, AuthenticationContext authenticationCon
* @return the matching SSL context factory (not {@code null})
*/
public SecurityFactory<SSLContext> getSSLContextFactory(URI uri, AuthenticationContext authenticationContext, String abstractType, String abstractTypeAuthority) {
Assert.checkNotNullParam("uri", uri);
Assert.checkNotNullParam("authenticationContext", authenticationContext);
final RuleNode<SecurityFactory<SSLContext>> node = authenticationContext.sslRuleMatching(uri, abstractType, abstractTypeAuthority);
if (node == null) return SSLContext::getDefault;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.security.auth.client;

import org.wildfly.client.config.ConfigXMLParseException;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLContextSpi;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.PrivilegedAction;
import java.security.SecureRandom;

/**
* SSLContextSpi that is used by ElytronClientDefaultSSLContextProvider
*/
public class DefaultSSLContextSpi extends SSLContextSpi {

private SSLContext configuredDefaultClientSSLContext;

public DefaultSSLContextSpi() throws GeneralSecurityException {
this(AuthenticationContext.captureCurrent());
}

public DefaultSSLContextSpi(String configPath) throws GeneralSecurityException, URISyntaxException, ConfigXMLParseException {
this(ElytronXmlParser.parseAuthenticationClientConfiguration(new URI(configPath)).create());
}

public DefaultSSLContextSpi(AuthenticationContext authenticationContext) throws GeneralSecurityException {
AuthenticationContextConfigurationClient AUTH_CONTEXT_CLIENT = AccessController.doPrivileged((PrivilegedAction<AuthenticationContextConfigurationClient>) AuthenticationContextConfigurationClient::new);
this.configuredDefaultClientSSLContext = AUTH_CONTEXT_CLIENT.getSSLContext(authenticationContext);
}

@Override
protected void engineInit(KeyManager[] keyManagers, TrustManager[] trustManagers, SecureRandom secureRandom) {
// ignore
}

@Override
protected SSLSocketFactory engineGetSocketFactory() {
return this.configuredDefaultClientSSLContext.getSocketFactory();
}

@Override
protected SSLServerSocketFactory engineGetServerSocketFactory() {
return this.configuredDefaultClientSSLContext.getServerSocketFactory();
}

@Override
protected SSLEngine engineCreateSSLEngine() {
return this.configuredDefaultClientSSLContext.createSSLEngine();
}

@Override
protected SSLEngine engineCreateSSLEngine(String s, int i) {
return this.configuredDefaultClientSSLContext.createSSLEngine(s, i);
}

@Override
protected SSLSessionContext engineGetServerSessionContext() {
return this.configuredDefaultClientSSLContext.getServerSessionContext();
}

@Override
protected SSLSessionContext engineGetClientSessionContext() {
return this.configuredDefaultClientSSLContext.getClientSessionContext();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.security.auth.client;

import org.wildfly.client.config.ConfigXMLParseException;
import org.wildfly.security.auth.client._private.ElytronMessages;
import static org.wildfly.security.auth.client._private.ElytronMessages.log;

import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.util.List;
import java.util.Map;

/**
* Provider that loads Elytron client configuration and provides default SSLContext which can be returned with SSLContext.getDefault() call.
* Default SSLContext is the configured SSL context that does not have any specific rule when it should be used, so it matches all rules.
*/
public final class ElytronClientDefaultSSLContextProvider extends Provider {

public static final String ELYTRON_CLIENT_DEFAULT_SSL_CONTEXT_PROVIDER_NAME = "ElytronClientDefaultSSLContextProvider";

public ElytronClientDefaultSSLContextProvider() {
this(null);
}

public ElytronClientDefaultSSLContextProvider(String configPath) {
super(ELYTRON_CLIENT_DEFAULT_SSL_CONTEXT_PROVIDER_NAME, 1.0, "Elytron client provider for default SSLContext");
putService(new ClientSSLContextProviderService(this, "SSLContext", "Default", "org.wildfly.security.auth.client.DefaultSSLContextSpi", null, null, configPath));
}

private static final class ClientSSLContextProviderService extends Provider.Service {
String configPath;
// this is Integer because we need to count the number of times entered
// entered.get()==2 means we requested this provider second time, creating a loop, so we throw an sslContextForSecurityProviderCreatesInfiniteLoop exception
// AuthenticationContextConfigurationClient receives sslContextForSecurityProviderCreatesInfiniteLoop exception during obtaining of default SSL context and will therefore request default SSL context from other providers
// after default SSL context from other provider is returned, we must check the entered variable again and throw an exception to inform users that this provider was unsuccessful because of invalid configuration
private final ThreadLocal<Integer> entered = new ThreadLocal<>();

ClientSSLContextProviderService(Provider provider, String type, String algorithm, String className, List<String> aliases,
Map<String, String> attributes, String configPath) {
super(provider, type, algorithm, className, aliases, attributes);
this.configPath = configPath;
}

/**
* There is a risk of looping if the Elytron client configuration is invalid.
* Loop will happen when Elytron client provider has configured default SSL context to be SSLContext::getDefault.
* Entered variable counts the number of entrances in order to avoid this loop.
* When it is equal or higher than 2 the NoSuchAlgorithmException will be thrown.
* When this exception is encountered, JVM tries to obtain default SSLContext from providers of lower priority
* and returns it to Elytron client as the default SSL context.
* Since we do not want to wrap the SSL context from other provider with this provider, we will throw an exception again
* which makes JVM escape this provider entirely and continue in the list of other providers.
*/
@Override
public Object newInstance(Object ignored) throws NoSuchAlgorithmException {
Integer enteredCountTmp = entered.get();
entered.set(enteredCountTmp == null ? 1 : enteredCountTmp + 1);
if (entered.get() >= 2) {
// we do not do clean up entered variable here because it is needed for the second check and possible throwing of second exception below
throw ElytronMessages.log.sslContextForSecurityProviderCreatesInfiniteLoop();
}

DefaultSSLContextSpi sslContext;
try {
if (configPath == null) {
sslContext = new DefaultSSLContextSpi(AuthenticationContext.captureCurrent());
} else {
sslContext = new DefaultSSLContextSpi(this.configPath);
}
// if we had an exception previously, then default SSLContext was still returned from other security provider of lower priority in
// AuthenticationContextConfigurationClient#getSSLContextFactory method.
// Since we do not want to wrap SSLContext from other provider with this provider, we need to check entered variable again
// and throw an exception which makes JVM ignore this provider and probe other providers again
if (entered.get() >= 2) {
throw ElytronMessages.log.sslContextForSecurityProviderCreatesInfiniteLoop();
}
} catch (URISyntaxException | ConfigXMLParseException | GeneralSecurityException e) {
if (e.getCause() instanceof FileNotFoundException) {
throw log.clientConfigurationFileNotFound();
}
throw new NoSuchAlgorithmException(e);
} finally {
entered.remove();
}
return sslContext;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -201,4 +201,10 @@ ConfigXMLParseException xmlUnableToIdentifyProvider(@Param Location location, St

@Message(id = 14004, value = "Password callback handling was unsuccessful")
ConfigXMLParseException passwordCallbackHandlingWasUnsuccessful();

@Message(id = 14005, value = "Default SSL context in security provider creates infinite loop")
NoSuchAlgorithmException sslContextForSecurityProviderCreatesInfiniteLoop();

@Message(id = 14007, value = "Configuration file path passed to ElytronClientDefaultSSLContextProvider not found")
IllegalArgumentException clientConfigurationFileNotFound();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package org.wildfly.security.auth.client;

import org.junit.Assert;
import org.junit.Test;

import javax.net.ssl.SSLContext;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

/**
* Test that configuration file passed to Elytron client provider has precedence over programmatic configuration
*/
public class DefaultSSLContextFromFileWorksAndHasPrecedenceTest {
private static final String CONFIG_FILE = "file:./src/test/resources/org/wildfly/security/auth/client/test-wildfly-config-client-default-sslcontext.xml";

@Test
public void testDefaultSSLContextFromFileWorksAndHasPrecedence() {
Security.insertProviderAt(new ElytronClientDefaultSSLContextProvider(CONFIG_FILE), 1);
Assert.assertNotNull(Security.getProvider("ElytronClientDefaultSSLContextProvider"));
AuthenticationContext.empty().run(() -> { // This will be ignored because file passed to provider has precedence
SSLContext defaultSSLContext = null;
try {
defaultSSLContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
Assert.fail("Obtaining of default SSLContext with both config file and programmatic configuration present threw NoSuchAlgorithmException exception.");
}
Assert.assertNotNull(defaultSSLContext);
Assert.assertNotNull(defaultSSLContext.getSocketFactory());
// if programmatic configuration was used, it would not find default ssl context configured and would delegate to other providers
// because the file was used, the default SSL context was present and returned with SSLContext.getDefault() call
Assert.assertEquals(defaultSSLContext.getProvider().getName(), ElytronClientDefaultSSLContextProvider.class.getSimpleName());
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package org.wildfly.security.auth.client;

import org.junit.Assert;
import org.junit.Test;

import javax.net.ssl.SSLContext;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

/**
* Test that default SSLContext provider will throw an exception when configured file path does not exist
*/
public class DefaultSSLContextNonexistentConfigFileTest {

private static final String CONFIG_FILE = "file:./src/test/resources/org/wildfly/security/auth/client/wildfly-config-invalid-path.xml";

@Test(expected = IllegalArgumentException.class)
public void defaultSSLContextNonexistentConfigFileTest() {
Security.insertProviderAt(new ElytronClientDefaultSSLContextProvider(CONFIG_FILE), 1);
Assert.assertNotNull(Security.getProvider("ElytronClientDefaultSSLContextProvider"));
AuthenticationContext authenticationContext = AuthenticationContext.captureCurrent();
authenticationContext.run(() -> {
SSLContext defaultSSLContext = null;
try {
defaultSSLContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
Assert.fail("Obtaining default SSL context from provider with invalid path threw incorrect exception");
}
Assert.assertNotNull(defaultSSLContext);
Assert.assertNotEquals(defaultSSLContext.getProvider().getName(), ElytronClientDefaultSSLContextProvider.class.getSimpleName()); // diff provider was used since elytron provider is looping
Assert.assertNotNull(defaultSSLContext.getSocketFactory());
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package org.wildfly.security.auth.client;

import org.junit.Assert;
import org.junit.Test;
import org.wildfly.client.config.ConfigXMLParseException;

import javax.net.ssl.SSLContext;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

/**
* Test that default SSLContext provider will silently delegate to other providers when configuration is looping or no default SSL context is configured
*/
public class DefaultSSLContextProviderDoesNotLoopTest {
private static final String CONFIG_FILE = "file:./src/test/resources/org/wildfly/security/auth/client/test-wildfly-config-default-ssl-context-invalid-looping.xml";

@Test
public void testDefaultSSLContextProviderDoesNotLoopTestCase() throws GeneralSecurityException, URISyntaxException, ConfigXMLParseException {
Security.insertProviderAt(new ElytronClientDefaultSSLContextProvider(), 1);
Assert.assertNotNull(Security.getProvider("ElytronClientDefaultSSLContextProvider"));
AuthenticationContext authenticationContext = ElytronXmlParser.parseAuthenticationClientConfiguration(new URI(CONFIG_FILE)).create();
authenticationContext.run(() -> {
SSLContext defaultSSLContext = null;
try {
defaultSSLContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
Assert.fail("Default SSL context provider should have delegated to other providers because configuration loops");
}
Assert.assertNotNull(defaultSSLContext);
Assert.assertNotEquals(defaultSSLContext.getProvider().getName(), ElytronClientDefaultSSLContextProvider.class.getSimpleName()); // diff provider was used since elytron provider is looping
Assert.assertNotNull(defaultSSLContext.getSocketFactory());
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package org.wildfly.security.auth.client;

import org.junit.Assert;
import org.junit.Test;
import org.wildfly.client.config.ConfigXMLParseException;

import javax.net.ssl.SSLContext;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

/**
* Test that default SSLContext from provider can use programmatic configuration
*/
public class DefaultSSLContextProviderProgrammaticConfigurationTest {
private static final String CONFIG_FILE = "file:./src/test/resources/org/wildfly/security/auth/client/test-wildfly-config-client-default-sslcontext.xml";

@Test
public void testDefaultSSLContextProgrammaticConfiguration() throws GeneralSecurityException, URISyntaxException, ConfigXMLParseException {
Security.insertProviderAt(new ElytronClientDefaultSSLContextProvider(), 1);
Assert.assertNotNull(Security.getProvider("ElytronClientDefaultSSLContextProvider"));
AuthenticationContext authenticationContext = ElytronXmlParser.parseAuthenticationClientConfiguration(new URI(CONFIG_FILE)).create();
authenticationContext.run(() -> {
SSLContext defaultSSLContext = null;
try {
defaultSSLContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
Assert.fail("Default SSL context from provider threw an exception when obtaining default SSL context from programmatic configuration ");
}
Assert.assertNotNull(defaultSSLContext);
Assert.assertEquals(defaultSSLContext.getProvider().getName(), ElytronClientDefaultSSLContextProvider.class.getSimpleName());
Assert.assertNotNull(defaultSSLContext.getSocketFactory());
});
}
}
Loading

0 comments on commit ff960fd

Please sign in to comment.