下面列出了javax.net.ssl.SSLParameters#setEndpointIdentificationAlgorithm ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private boolean overrideHostnameVerificationForClient(SSLParameters params) {
String configuredAlgorithm = params.getEndpointIdentificationAlgorithm();
switch (hostnameVerification) {
case ENABLED:
if (!"HTTPS".equals(configuredAlgorithm)) {
params.setEndpointIdentificationAlgorithm("HTTPS");
return true;
}
return false;
case DISABLED:
if (configuredAlgorithm != null && !configuredAlgorithm.isEmpty()) {
params.setEndpointIdentificationAlgorithm(""); // disable any configured endpoint identification algorithm
return true;
}
return false;
default:
throw new IllegalStateException("Unknown host verification type: " + hostnameVerification);
}
}
@Override
public SSLEngine serverSslEngine(String peerHost, int peerPort) {
try {
SSLEngine sslEngine = upstreamServerSslContext.get().newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);
// support SNI by setting the endpoint identification algorithm. this requires Java 7+.
SSLParameters sslParams = new SSLParameters();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
}
sslEngine.setSSLParameters(sslParams);
return sslEngine;
} catch (RuntimeException e) {
throw new MitmException("Error creating SSLEngine for connection to upstream server: " + peerHost + ":" + peerPort, e);
}
}
private ChannelHandler getClientHandler(
X509Certificate trustedCertificate, PrivateKey privateKey, X509Certificate certificate) {
return new ChannelInitializer<LocalChannel>() {
@Override
protected void initChannel(LocalChannel ch) throws Exception {
SslContextBuilder sslContextBuilder =
SslContextBuilder.forClient().trustManager(trustedCertificate).sslProvider(sslProvider);
if (privateKey != null && certificate != null) {
sslContextBuilder.keyManager(privateKey, certificate);
}
SslHandler sslHandler =
sslContextBuilder.build().newHandler(ch.alloc(), SSL_HOST, SSL_PORT);
// Enable hostname verification.
SSLEngine sslEngine = sslHandler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
ch.pipeline().addLast(sslHandler);
}
};
}
@Override
public final synchronized SSLParameters getSSLParameters() {
SSLParameters sslParameters = super.getSSLParameters();
int version = PlatformDependent.javaVersion();
if (version >= 7) {
sslParameters.setEndpointIdentificationAlgorithm(endPointIdentificationAlgorithm);
Java7SslParametersUtils.setAlgorithmConstraints(sslParameters, algorithmConstraints);
if (version >= 8) {
if (sniHostNames != null) {
Java8SslUtils.setSniHostNames(sslParameters, sniHostNames);
}
if (!isDestroyed()) {
Java8SslUtils.setUseCipherSuitesOrder(
sslParameters, (SSL.getOptions(ssl) & SSL.SSL_OP_CIPHER_SERVER_PREFERENCE) != 0);
}
Java8SslUtils.setSNIMatchers(sslParameters, matchers);
}
}
return sslParameters;
}
/**
* Create a new OpenSSL SSLEngine instance in client mode from the given SSLContext and
* TransportOptions instances.
*
* @param allocator
* the Netty ByteBufAllocator to use to create the OpenSSL engine
* @param remote
* the URI of the remote peer that will be used to initialize the engine, may be null if none should.
* @param context
* the Netty SslContext to use when creating the engine.
* @param options
* the TransportOptions to use to configure the new SSLEngine.
*
* @return a new Netty managed SSLEngine instance in client mode.
*
* @throws Exception if an error occurs while creating the new SSLEngine.
*/
public static SSLEngine createOpenSslEngine(ByteBufAllocator allocator, URI remote, SslContext context, TransportOptions options) throws Exception {
SSLEngine engine = null;
if (allocator == null) {
throw new IllegalArgumentException("OpenSSL engine requires a valid ByteBufAllocator to operate");
}
if (remote == null) {
engine = context.newEngine(allocator);
} else {
engine = context.newEngine(allocator, remote.getHost(), remote.getPort());
}
engine.setEnabledProtocols(buildEnabledProtocols(engine, options));
engine.setEnabledCipherSuites(buildEnabledCipherSuites(engine, options));
engine.setUseClientMode(true);
if (options.isVerifyHost()) {
SSLParameters sslParameters = engine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
engine.setSSLParameters(sslParameters);
}
return engine;
}
public void test_SSLSocket_getSSLParameters() throws Exception {
SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket ssl = (SSLSocket) sf.createSocket();
SSLParameters p = ssl.getSSLParameters();
assertNotNull(p);
String[] cipherSuites = p.getCipherSuites();
assertNotSame(cipherSuites, ssl.getEnabledCipherSuites());
assertEquals(Arrays.asList(cipherSuites), Arrays.asList(ssl.getEnabledCipherSuites()));
String[] protocols = p.getProtocols();
assertNotSame(protocols, ssl.getEnabledProtocols());
assertEquals(Arrays.asList(protocols), Arrays.asList(ssl.getEnabledProtocols()));
assertEquals(p.getWantClientAuth(), ssl.getWantClientAuth());
assertEquals(p.getNeedClientAuth(), ssl.getNeedClientAuth());
assertNull(p.getEndpointIdentificationAlgorithm());
p.setEndpointIdentificationAlgorithm(null);
assertNull(p.getEndpointIdentificationAlgorithm());
p.setEndpointIdentificationAlgorithm("HTTPS");
assertEquals("HTTPS", p.getEndpointIdentificationAlgorithm());
p.setEndpointIdentificationAlgorithm("FOO");
assertEquals("FOO", p.getEndpointIdentificationAlgorithm());
}
@Bean
@Primary
@Autowired
public HttpClient httpClientWithOutProxy(TrustManager[] trustAllCertificates, ExecutorService httpclientExecutorService) throws NoSuchAlgorithmException, KeyManagementException {
SSLParameters sslParams = new SSLParameters();
sslParams.setEndpointIdentificationAlgorithm("");
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCertificates, new SecureRandom());
return HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
// .sslParameters(sslParams)
// .sslContext(sc)
.connectTimeout(Duration.ofSeconds(30))
// .proxy(ProxySelector.of(new InetSocketAddress("127.0.0.1", 8888)))
.executor(httpclientExecutorService)
.followRedirects(HttpClient.Redirect.NEVER)
.build();
}
/**
* Create a new SSLEngine instance in client mode from the given SSLContext and
* TransportSslOptions instances.
*
* @param remote
* the URI of the remote peer that will be used to initialize the engine, may be null
* if none should.
* @param context
* the SSLContext to use when creating the engine.
* @param options
* the TransportSslOptions to use to configure the new SSLEngine.
*
* @return a new SSLEngine instance in client mode.
*
* @throws Exception
* if an error occurs while creating the new SSLEngine.
*/
public static SSLEngine createSslEngine(URI remote, SSLContext context, NettyTransportSslOptions options) throws Exception {
SSLEngine engine = null;
if (remote == null) {
engine = context.createSSLEngine();
} else {
engine = context.createSSLEngine(remote.getHost(), remote.getPort());
}
engine.setEnabledProtocols(buildEnabledProtocols(engine, options));
engine.setEnabledCipherSuites(buildEnabledCipherSuites(engine, options));
engine.setUseClientMode(true);
if (options.isVerifyHost()) {
SSLParameters sslParameters = engine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
engine.setSSLParameters(sslParameters);
}
return engine;
}
@Override
public SSLEngine serverSslEngine(String peerHost, int peerPort) {
try {
SSLEngine sslEngine = upstreamServerSslContext.get().newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);
// support SNI by setting the endpoint identification algorithm. this requires Java 7+.
SSLParameters sslParams = new SSLParameters();
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParams);
return sslEngine;
} catch (RuntimeException e) {
throw new MitmException("Error creating SSLEngine for connection to upstream server: " + peerHost + ":" + peerPort, e);
}
}
/**
* Returns the SSLParameters in effect for newly accepted connections.
*/
@Override
synchronized public SSLParameters getSSLParameters() {
SSLParameters params = super.getSSLParameters();
// the super implementation does not handle the following parameters
params.setEndpointIdentificationAlgorithm(identificationProtocol);
params.setAlgorithmConstraints(algorithmConstraints);
params.setSNIMatchers(sniMatchers);
params.setUseCipherSuitesOrder(preferLocalCipherSuites);
return params;
}
/**
* Create {@link SSLEngine} for given host name and port number.
* This engine manages the handshake process and encryption/decryption with this remote host.
* @param peerHost The remote host name
* @param peerPort The remote port number
* @param mode The local SSL mode, Client or Server
* @return SSLEngine
*/
@Override
public SSLEngine createSSLEngine(String peerHost, int peerPort, Mode mode) {
SSLEngine sslEngine = sslContext.createSSLEngine(peerHost, peerPort);
if (cipherSuites != null) {
sslEngine.setEnabledCipherSuites(cipherSuites);
}
if (enabledProtocols != null) {
sslEngine.setEnabledProtocols(enabledProtocols);
}
if (mode == Mode.SERVER) {
sslEngine.setUseClientMode(false);
switch (clientAuth) {
case REQUIRED:
sslEngine.setNeedClientAuth(true);
break;
case REQUESTED:
sslEngine.setWantClientAuth(true);
break;
}
} else {
sslEngine.setUseClientMode(true);
SSLParameters sslParams = sslEngine.getSSLParameters();
sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
sslEngine.setSSLParameters(sslParams);
}
return sslEngine;
}
/**
* Returns the SSLParameters in effect for newly accepted connections.
*/
@Override
synchronized public SSLParameters getSSLParameters() {
SSLParameters params = super.getSSLParameters();
// the super implementation does not handle the following parameters
params.setEndpointIdentificationAlgorithm(identificationProtocol);
params.setAlgorithmConstraints(algorithmConstraints);
params.setSNIMatchers(sniMatchers);
params.setUseCipherSuitesOrder(preferLocalCipherSuites);
return params;
}
@Override
protected void initChannel(C channel) throws Exception {
checkNotNull(hostProvider.apply(channel), "Cannot obtain SSL host for channel: %s", channel);
checkNotNull(portProvider.apply(channel), "Cannot obtain SSL port for channel: %s", channel);
SslContextBuilder sslContextBuilder =
SslContextBuilder.forClient()
.sslProvider(sslProvider)
.trustManager(
trustedCertificates == null || trustedCertificates.isEmpty()
? null
: trustedCertificates.toArray(new X509Certificate[0]));
if (privateKeySupplier != null && certificateChainSupplier != null) {
sslContextBuilder.keyManager(
privateKeySupplier.get(), certificateChainSupplier.get().toArray(new X509Certificate[0]));
}
SslHandler sslHandler =
sslContextBuilder
.build()
.newHandler(channel.alloc(), hostProvider.apply(channel), portProvider.apply(channel));
// Enable hostname verification.
SSLEngine sslEngine = sslHandler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
channel.pipeline().addLast(sslHandler);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket)
throws CertificateException {
if (socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket) socket;
SSLParameters sslParams = sslSocket.getSSLParameters();
if (sslParams != null) {
sslParams.setEndpointIdentificationAlgorithm(null);
sslSocket.setSSLParameters(sslParams);
}
}
delegate.checkServerTrusted(chain, authType, socket);
verifySubjectAltNameInChain(chain);
}
/**
* Create a Channel Initializer which is to to setup {@link ChannelPipeline}.
*/
@VisibleForTesting
ChannelInitializer<SocketChannel> getChannelInitializer(final PravegaNodeUri location,
final FlowHandler handler) {
final SslContext sslCtx = getSslContext();
return new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());
if (clientConfig.isValidateHostName()) {
SSLEngine sslEngine = sslHandler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
}
p.addLast(sslHandler);
}
p.addLast(
new ExceptionLoggingHandler(location.getEndpoint()),
new CommandEncoder(handler::getAppendBatchSizeTracker, metricNotifier),
new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4),
new CommandDecoder(),
handler);
}
};
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine sslEngine)
throws CertificateException {
SSLParameters sslParams = sslEngine.getSSLParameters();
if (sslParams != null) {
sslParams.setEndpointIdentificationAlgorithm(null);
sslEngine.setSSLParameters(sslParams);
}
delegate.checkServerTrusted(chain, authType, sslEngine);
verifySubjectAltNameInChain(chain);
}
@Override
public SSLEngine createSSLEngine(String peerHost, int peerPort, Mode mode) {
SslContext context = mode == Mode.CLIENT ? nettyClientSslContext : nettyServerSslContext;
SSLEngine sslEngine = context.newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);
if (mode == Mode.CLIENT) {
SSLParameters sslParams = sslEngine.getSSLParameters();
sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
sslEngine.setSSLParameters(sslParams);
}
return sslEngine;
}
@Override
protected void handlerAdded0(ChannelHandlerContext ctx) {
SSLEngine sslEngine = sslContext.newEngine(ctx.alloc(), host, port);
SSLParameters sslParams = sslEngine.getSSLParameters();
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParams);
ctx.pipeline().addBefore(ctx.name(), /* name= */ null, this.executor != null
? new SslHandler(sslEngine, false, this.executor)
: new SslHandler(sslEngine, false));
}
private SSLParameters buildTrustManagerAndGetSslParameters()
throws CertificateException, IOException, CertStoreException {
X509Certificate[] caCerts =
CertificateUtils.toX509Certificates(TestUtils.loadCert(CA_PEM_FILE));
trustManager = SdsTrustManagerFactory.createSdsX509TrustManager(caCerts,
null);
when(mockSession.getProtocol()).thenReturn("TLSv1.2");
when(mockSession.getPeerHost()).thenReturn("peer-host-from-mock");
SSLParameters sslParams = new SSLParameters();
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
return sslParams;
}
public SSLParameters enableHostNameVerification(SSLParameters sslParameters) {
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
return sslParameters;
}