下面列出了javax.net.ssl.SSLContext#setDefault ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@After
public void teardown() throws Exception {
if (defaultSSLContext != null) {
SSLContext.setDefault(defaultSSLContext);
HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
}
if (restClient != null) {
restClient.shutdown(timeout);
restClient = null;
}
if (serverEndpoint != null) {
serverEndpoint.closeAsync().get(timeout.getSize(), timeout.getUnit());
serverEndpoint = null;
}
}
@After
public void teardown() throws Exception {
if (defaultSSLContext != null) {
SSLContext.setDefault(defaultSSLContext);
HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
}
if (restClient != null) {
restClient.shutdown(timeout);
restClient = null;
}
if (serverEndpoint != null) {
serverEndpoint.closeAsync().get(timeout.getSize(), timeout.getUnit());
serverEndpoint = null;
}
}
@Test
public void testBrowserModProxyResponseFiltering() {
List<String> content = new ArrayList<>();
LocalTrustStoreBuilder localTrustStoreBuilder = new LocalTrustStoreBuilder();
SSLContext sslContext = localTrustStoreBuilder.createSSLContext();
SSLContext.setDefault(sslContext);
ProxyPool.setupBrowserMobProxy();
SystemProxy.setupProxy();
BrowserMobProxy proxy = ProxyPool.getProxy();
proxy.enableHarCaptureTypes(CaptureType.RESPONSE_CONTENT);
proxy.newHar();
proxy.addResponseFilter((request, contents, messageInfo) -> {
LOGGER.info("Requested resource caught contents: " + contents.getTextContents());
if (contents.getTextContents().contains(filterKey)) {
content.add(contents.getTextContents());
}
});
makeHttpRequest(testUrl, requestMethod);
Assert.assertNotNull(proxy.getHar(), "Har is unexpectedly null!");
Assert.assertEquals(content.size(), 1,"Filtered response number is not as expected!");
Assert.assertTrue(content.get(0).contains(filterKey), "Response doesn't contain expected key!");
}
/**
* Constructs a cluster with the specified sslConfigs, runs {@link #checkClusterWithCollectionCreations},
* then verifies that if we modify the default SSLContext (mimicing <code>javax.net.ssl.*</code>
* sysprops set on JVM startup) and reset to the default HttpClientBuilder, new HttpSolrClient instances
* will still be able to talk to our servers.
*
* @see SSLContext#setDefault
* @see HttpClientUtil#resetHttpClientBuilder
* @see #checkClusterWithCollectionCreations
*/
private void checkClusterWithNodeReplacement(SSLTestConfig sslConfig) throws Exception {
final JettyConfig config = JettyConfig.builder().withSSLConfig(sslConfig.buildServerSSLConfig()).build();
final MiniSolrCloudCluster cluster = new MiniSolrCloudCluster(NUM_SERVERS, createTempDir(), config);
try {
checkClusterWithCollectionCreations(cluster, sslConfig);
// Change the defaul SSLContext to match our test config, or to match our original system default if
// our test config doesn't use SSL, and reset HttpClientUtil to it's defaults so it picks up our
// SSLContext that way.
SSLContext.setDefault( sslConfig.isSSLMode() ? sslConfig.buildClientSSLContext() : DEFAULT_SSL_CONTEXT);
System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME,
Boolean.toString(sslConfig.getCheckPeerName()));
HttpClientUtil.resetHttpClientBuilder();
Http2SolrClient.resetSslContextFactory();
// recheck that we can communicate with all the jetty instances in our cluster
checkClusterJettys(cluster, sslConfig);
} finally {
cluster.shutdown();
}
}
public static void reloadSSLContext() {
List<Map.Entry<String, String>> uriWithcertificatesToTrust = getAllUriWithCertificate(getNodesWithCertificates());
if (uriWithcertificatesToTrust.size() > 0) {
SSLContext customSslContext = CustomSSLContext.getSslContext(uriWithcertificatesToTrust);
SSLContext.setDefault(customSslContext);
}
}
@Test
public void testPropertiesSSLOptions() throws Exception {
// don't use default for tests, issues with forcing algorithm exception in other tests break it
SSLContext.setDefault(TestSSLUtils.createTestSSLContext());
Properties props = new Properties();
props.setProperty(Options.PROP_SECURE, "true");
Options o = new Options.Builder(props).build();
assertEquals("default verbose", false, o.isVerbose()); // One from a different type
assertNotNull("property context", o.getSslContext());
}
/**
* Method that bypasses every SSL certificate verification and accepts every
* connection with any SSL protected device that ONOS has an interaction with.
* Needs addressing for secutirty purposes.
*
* @throws NoSuchAlgorithmException if algorithm specified is not available
* @throws KeyManagementException if unable to use the key
*/
//FIXME redo for security purposes.
protected static void enableSslCert() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext ctx = SSLContext.getInstance(TLS);
ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> {
//FIXME better way to do this.
return true;
});
}
@Test
public void testOneWaySSLUsingDefaultSslContext() throws Exception {
createCustomSslServer();
String text = RandomUtil.randomString();
tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
tc.getParams().put(TransportConstants.USE_DEFAULT_SSL_CONTEXT_PROP_NAME, true);
SSLContext.setDefault(new SSLSupport()
.setTruststoreProvider(storeType)
.setTruststorePath(CLIENT_SIDE_TRUSTSTORE)
.setTruststorePassword(PASSWORD)
.createContext());
ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc));
ClientSessionFactory sf = addSessionFactory(createSessionFactory(locator));
ClientSession session = addClientSession(sf.createSession(false, true, true));
session.createQueue(new QueueConfiguration(CoreClientOverOneWaySSLTest.QUEUE).setDurable(false));
ClientProducer producer = addClientProducer(session.createProducer(CoreClientOverOneWaySSLTest.QUEUE));
ClientMessage message = createTextMessage(session, text);
producer.send(message);
ClientConsumer consumer = addClientConsumer(session.createConsumer(CoreClientOverOneWaySSLTest.QUEUE));
session.start();
ClientMessage m = consumer.receive(1000);
Assert.assertNotNull(m);
Assert.assertEquals(text, m.getBodyBuffer().readString());
}
public static void acceptUntrusted() {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
SSLContext.setDefault(sslContext);
} catch (Exception ex) {
throw new RuntimeException("Could not change SSL TrustManager to accept arbitrary certificates", ex);
}
}
public static void enableAnySSL() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private SlaveConnectionManager() {
if ( needToInitializeSSLContext() ) {
try {
SSLContext context = SSLContext.getInstance( SSL );
context.init( new KeyManager[ 0 ], new X509TrustManager[] { getDefaultTrustManager() }, new SecureRandom() );
SSLContext.setDefault( context );
} catch ( Exception e ) {
new LogChannel( "SlaveConnectionManager" )
.logDebug( "Default SSL context hasn't been initialized.\n" + e.getMessage() );
}
}
manager = new PoolingHttpClientConnectionManager();
manager.setDefaultMaxPerRoute( 100 );
manager.setMaxTotal( 200 );
}
/**
* Initializes the SSL Context
*/
private void initSSLConnection() throws NoSuchAlgorithmException, UnrecoverableKeyException,
KeyStoreException, KeyManagementException {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
keyManagerFactory.init(keyStore, keyStorePassword);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
trustManagerFactory.init(trustStore);
// Create and initialize SSLContext for HTTPS communication
sslContext = SSLContext.getInstance(SSLV3);
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
SSLContext.setDefault(sslContext);
}
public static void enableAnySSL() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Before
public void setup() throws Exception {
config.setString(WebOptions.UPLOAD_DIR, temporaryFolder.newFolder().getCanonicalPath());
defaultSSLContext = SSLContext.getDefault();
defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
final SSLContext sslClientContext = SSLUtils.createRestClientSSLContext(config);
if (sslClientContext != null) {
SSLContext.setDefault(sslClientContext);
HttpsURLConnection.setDefaultSSLSocketFactory(sslClientContext.getSocketFactory());
}
RestServerEndpointConfiguration serverConfig = RestServerEndpointConfiguration.fromConfiguration(config);
RestClientConfiguration clientConfig = RestClientConfiguration.fromConfiguration(config);
RestfulGateway mockRestfulGateway = mock(RestfulGateway.class);
final GatewayRetriever<RestfulGateway> mockGatewayRetriever = () ->
CompletableFuture.completedFuture(mockRestfulGateway);
testHandler = new TestHandler(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
TestVersionHandler testVersionHandler = new TestVersionHandler(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
TestVersionSelectionHandler1 testVersionSelectionHandler1 = new TestVersionSelectionHandler1(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
TestVersionSelectionHandler2 testVersionSelectionHandler2 = new TestVersionSelectionHandler2(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
testUploadHandler = new TestUploadHandler(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
final StaticFileServerHandler<RestfulGateway> staticFileServerHandler = new StaticFileServerHandler<>(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT,
temporaryFolder.getRoot());
final List<Tuple2<RestHandlerSpecification, ChannelInboundHandler>> handlers = Arrays.asList(
Tuple2.of(new TestHeaders(), testHandler),
Tuple2.of(TestUploadHeaders.INSTANCE, testUploadHandler),
Tuple2.of(testVersionHandler.getMessageHeaders(), testVersionHandler),
Tuple2.of(testVersionSelectionHandler1.getMessageHeaders(), testVersionSelectionHandler1),
Tuple2.of(testVersionSelectionHandler2.getMessageHeaders(), testVersionSelectionHandler2),
Tuple2.of(WebContentHandlerSpecification.getInstance(), staticFileServerHandler));
serverEndpoint = new TestRestServerEndpoint(serverConfig, handlers);
restClient = new TestRestClient(clientConfig);
serverEndpoint.start();
serverAddress = serverEndpoint.getServerAddress();
}
@Before
public void setup() throws Exception {
config.setString(WebOptions.UPLOAD_DIR, temporaryFolder.newFolder().getCanonicalPath());
defaultSSLContext = SSLContext.getDefault();
defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
final SSLContext sslClientContext = SSLUtils.createRestSSLContext(config, true);
if (sslClientContext != null) {
SSLContext.setDefault(sslClientContext);
HttpsURLConnection.setDefaultSSLSocketFactory(sslClientContext.getSocketFactory());
}
RestServerEndpointConfiguration serverConfig = RestServerEndpointConfiguration.fromConfiguration(config);
RestClientConfiguration clientConfig = RestClientConfiguration.fromConfiguration(config);
RestfulGateway mockRestfulGateway = mock(RestfulGateway.class);
final GatewayRetriever<RestfulGateway> mockGatewayRetriever = () ->
CompletableFuture.completedFuture(mockRestfulGateway);
testHandler = new TestHandler(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
TestVersionHandler testVersionHandler = new TestVersionHandler(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
TestVersionSelectionHandler1 testVersionSelectionHandler1 = new TestVersionSelectionHandler1(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
TestVersionSelectionHandler2 testVersionSelectionHandler2 = new TestVersionSelectionHandler2(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
testUploadHandler = new TestUploadHandler(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
final StaticFileServerHandler<RestfulGateway> staticFileServerHandler = new StaticFileServerHandler<>(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT,
temporaryFolder.getRoot());
final List<Tuple2<RestHandlerSpecification, ChannelInboundHandler>> handlers = Arrays.asList(
Tuple2.of(new TestHeaders(), testHandler),
Tuple2.of(TestUploadHeaders.INSTANCE, testUploadHandler),
Tuple2.of(testVersionHandler.getMessageHeaders(), testVersionHandler),
Tuple2.of(testVersionSelectionHandler1.getMessageHeaders(), testVersionSelectionHandler1),
Tuple2.of(testVersionSelectionHandler2.getMessageHeaders(), testVersionSelectionHandler2),
Tuple2.of(WebContentHandlerSpecification.getInstance(), staticFileServerHandler));
serverEndpoint = new TestRestServerEndpoint(serverConfig, handlers);
restClient = new TestRestClient(clientConfig);
serverEndpoint.start();
serverAddress = serverEndpoint.getServerAddress();
}
@Override
protected Connector getConnector(String host, int port) throws IOException {
org.apache.commons.configuration.Configuration config = getConfiguration();
SSLContext sslContext = getSSLContext();
if (sslContext != null) {
SSLContext.setDefault(sslContext);
}
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(config.getString(KEYSTORE_FILE_KEY,
System.getProperty(KEYSTORE_FILE_KEY, DEFAULT_KEYSTORE_FILE_LOCATION)));
sslContextFactory.setKeyStorePassword(getPassword(config, KEYSTORE_PASSWORD_KEY));
sslContextFactory.setKeyManagerPassword(getPassword(config, SERVER_CERT_PASSWORD_KEY));
sslContextFactory.setTrustStorePath(config.getString(TRUSTSTORE_FILE_KEY,
System.getProperty(TRUSTSTORE_FILE_KEY, DEFATULT_TRUSTORE_FILE_LOCATION)));
sslContextFactory.setTrustStorePassword(getPassword(config, TRUSTSTORE_PASSWORD_KEY));
sslContextFactory.setWantClientAuth(config.getBoolean(CLIENT_AUTH_KEY, Boolean.getBoolean(CLIENT_AUTH_KEY)));
List<Object> cipherList = config.getList(ATLAS_SSL_EXCLUDE_CIPHER_SUITES, DEFAULT_CIPHER_SUITES);
sslContextFactory.setExcludeCipherSuites(cipherList.toArray(new String[cipherList.size()]));
sslContextFactory.setRenegotiationAllowed(false);
String[] excludedProtocols = config.containsKey(ATLAS_SSL_EXCLUDE_PROTOCOLS) ?
config.getStringArray(ATLAS_SSL_EXCLUDE_PROTOCOLS) : DEFAULT_EXCLUDE_PROTOCOLS;
if (excludedProtocols != null && excludedProtocols.length > 0) {
sslContextFactory.addExcludeProtocols(excludedProtocols);
}
// SSL HTTP Configuration
// HTTP Configuration
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
final int bufferSize = AtlasConfiguration.WEBSERVER_REQUEST_BUFFER_SIZE.getInt();
http_config.setSecurePort(port);
http_config.setRequestHeaderSize(bufferSize);
http_config.setResponseHeaderSize(bufferSize);
http_config.setSendServerVersion(true);
http_config.setSendDateHeader(false);
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(https_config));
sslConnector.setPort(port);
server.addConnector(sslConnector);
return sslConnector;
}
@Before
public void setup() throws Exception {
config.setString(WebOptions.UPLOAD_DIR, temporaryFolder.newFolder().getCanonicalPath());
defaultSSLContext = SSLContext.getDefault();
defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
final SSLContext sslClientContext = SSLUtils.createRestSSLContext(config, true);
if (sslClientContext != null) {
SSLContext.setDefault(sslClientContext);
HttpsURLConnection.setDefaultSSLSocketFactory(sslClientContext.getSocketFactory());
}
RestServerEndpointConfiguration serverConfig = RestServerEndpointConfiguration.fromConfiguration(config);
RestClientConfiguration clientConfig = RestClientConfiguration.fromConfiguration(config);
RestfulGateway mockRestfulGateway = mock(RestfulGateway.class);
final GatewayRetriever<RestfulGateway> mockGatewayRetriever = () ->
CompletableFuture.completedFuture(mockRestfulGateway);
testHandler = new TestHandler(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
TestVersionHandler testVersionHandler = new TestVersionHandler(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
TestVersionSelectionHandler1 testVersionSelectionHandler1 = new TestVersionSelectionHandler1(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
TestVersionSelectionHandler2 testVersionSelectionHandler2 = new TestVersionSelectionHandler2(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
testUploadHandler = new TestUploadHandler(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT);
final StaticFileServerHandler<RestfulGateway> staticFileServerHandler = new StaticFileServerHandler<>(
mockGatewayRetriever,
RpcUtils.INF_TIMEOUT,
temporaryFolder.getRoot());
final List<Tuple2<RestHandlerSpecification, ChannelInboundHandler>> handlers = Arrays.asList(
Tuple2.of(new TestHeaders(), testHandler),
Tuple2.of(TestUploadHeaders.INSTANCE, testUploadHandler),
Tuple2.of(testVersionHandler.getMessageHeaders(), testVersionHandler),
Tuple2.of(testVersionSelectionHandler1.getMessageHeaders(), testVersionSelectionHandler1),
Tuple2.of(testVersionSelectionHandler2.getMessageHeaders(), testVersionSelectionHandler2),
Tuple2.of(WebContentHandlerSpecification.getInstance(), staticFileServerHandler));
serverEndpoint = new TestRestServerEndpoint(serverConfig, handlers);
restClient = new TestRestClient(clientConfig);
serverEndpoint.start();
serverAddress = serverEndpoint.getServerAddress();
}
public void j2objcNotImplemented_test_SSLSocketFactory_getDefault_cacheInvalidate()
throws Exception {
String origProvider = resetSslProvider();
try {
SocketFactory sf1 = SSLSocketFactory.getDefault();
assertNotNull(sf1);
assertTrue(SSLSocketFactory.class.isAssignableFrom(sf1.getClass()));
Provider fakeProvider = new FakeSSLSocketProvider();
SocketFactory sf4 = null;
SSLContext origContext = null;
try {
origContext = SSLContext.getDefault();
Security.insertProviderAt(fakeProvider, 1);
SSLContext.setDefault(SSLContext.getInstance("Default", fakeProvider));
sf4 = SSLSocketFactory.getDefault();
assertNotNull(sf4);
assertTrue(SSLSocketFactory.class.isAssignableFrom(sf4.getClass()));
assertFalse(sf1.getClass() + " should not be " + sf4.getClass(),
sf1.getClass().equals(sf4.getClass()));
} finally {
SSLContext.setDefault(origContext);
Security.removeProvider(fakeProvider.getName());
}
SocketFactory sf3 = SSLSocketFactory.getDefault();
assertNotNull(sf3);
assertTrue(SSLSocketFactory.class.isAssignableFrom(sf3.getClass()));
assertTrue(sf1.getClass() + " should be " + sf3.getClass(),
sf1.getClass().equals(sf3.getClass()));
if (!StandardNames.IS_RI) {
Security.setProperty(SSL_PROPERTY, FakeSSLSocketFactory.class.getName());
SocketFactory sf2 = SSLSocketFactory.getDefault();
assertNotNull(sf2);
assertTrue(SSLSocketFactory.class.isAssignableFrom(sf2.getClass()));
assertFalse(sf2.getClass().getName() + " should not be " + Security.getProperty(SSL_PROPERTY),
sf1.getClass().equals(sf2.getClass()));
assertTrue(sf2.getClass().equals(sf4.getClass()));
resetSslProvider();
}
} finally {
Security.setProperty(SSL_PROPERTY, origProvider);
}
}
public static void initialize(Context context) {
try {
synchronized (lock) {
if (initialized) {
return;
}
initialized = true;
// GMS Conscrypt is already initialized, from outside ion. Leave it alone.
if (Security.getProvider(GMS_PROVIDER) != null) {
success = true;
return;
}
SSLContext originalDefaultContext = SSLContext.getDefault();
SSLSocketFactory originalDefaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
try {
Class<?> providerInstaller = Class.forName("com.google.android.gms.security.ProviderInstaller");
Method mInsertProvider = providerInstaller.getDeclaredMethod("installIfNeeded", Context.class);
mInsertProvider.invoke(null, context);
} catch (Throwable ignored) {
Context gms = context
.createPackageContext("com.google.android.gms", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
gms.getClassLoader().loadClass("com.google.android.gms.common.security.ProviderInstallerImpl")
.getMethod("insertProvider", Context.class).invoke(null, context);
}
Provider[] providers = Security.getProviders();
Provider provider = Security.getProvider(GMS_PROVIDER);
Security.removeProvider(GMS_PROVIDER);
Security.insertProviderAt(provider, providers.length);
SSLContext.setDefault(originalDefaultContext);
HttpsURLConnection.setDefaultSSLSocketFactory(originalDefaultSSLSocketFactory);
success = true;
// try {
// SSLContext sslContext = null;
// try {
// sslContext = SSLContext.getInstance("TLS", GMS_PROVIDER);
// }
// catch (Exception e) {
// }
// if (sslContext == null)
// sslContext = SSLContext.getInstance("TLS");
// sslContext.init(null, null, null);
// }
// catch (Exception e) {
// }
}
} catch (Exception e) {
}
}
@After
public void reset() throws Exception {
SSLContext.setDefault(this.defaultContext);
}