How to disable SSL validation in spring-boot-starter-websocket - java

I am using dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>3.0.1</version>
</dependency>
and can't disable self-signed certificate verification
My code
StandardWebSocketClient client = new StandardWebSocketClient();
client.setUserProperties(Map.of(Constants.SSL_CONTEXT_PROPERTY, sslContext));
WebSocketStompClient stompClient = new WebSocketStompClient(client);
stompClient.setMessageConverter(new MappingJackson2MessageConverter());
stompClient.setInboundMessageSizeLimit(200000);
ClientWebsocketHandler sessionHandler = new ClientWebsocketHandler();
WebSocketHttpHeaders handshakeHeaders = new WebSocketHttpHeaders();
StompHeaders connectHeaders = new StompHeaders();
connectHeaders.add("username", "username");
connectHeaders.add("password", "password");
ListenableFuture<StompSession> connect = stompClient.connect("wss://111.111.11.111:8080/chat", handshakeHeaders, connectHeaders, sessionHandler);
i always get an error
Caused by: javax.net.ssl.SSLHandshakeException: No subject alternative names present
Browser connects successfully http://jxy.me/websocket-debug-tool/
i tried different ways
i added certificate with cacerts jdk
private static void disableSslVerification() {
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = (hostname, session) -> true;
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
}
StandardWebSocketClient client = new StandardWebSocketClient();
client.setUserProperties(Map.of(Constants.SSL_CONTEXT_PROPERTY, sslContext));
enter image description here

Related

Swagger generated client code not able to call a https localhost endpoint

I have a pretty brittle and complicated development setup. I have a ssh tunnel to a machine that exposes a machine on that network, when ssh tunnel is in place, I can access my api easily via Postman or curl like this.
curl -X GET -u admin:admin123 -k "https://172.23.1.175/api/storage/aggregates/?fields=space&return_records=true&return_timeout=15" -H "accept: application/hal+json"
My client code is created via swagger, for development purpose I want to be able to try within my java application in IntelliJ to make the actual API call. I know this is completely frowned up on. The error I get is this:
io.swagger.ontap.client.ApiException: javax.net.ssl.SSLPeerUnverifiedException: Hostname localhost not verified:
certificate: sha1/o6KF0+STnresD1HaPMVoHNMgwpY=
DN: C=US, CN=ontapcloud-net0ejmuaf-1
subjectAltNames: []
This is a newer error after I tried to import the cert to my java config, before it was like this.
cause javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Can the code below be modified to accommodate so the request will pass through?
private void applySslSettings() {
try {
TrustManager[] trustManagers = null;
HostnameVerifier hostnameVerifier = null;
System.out.println("verifyingSsl: " + verifyingSsl);
if (!verifyingSsl) {
TrustManager trustAll = new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
#Override
public X509Certificate[] getAcceptedIssuers() { return null; }
};
SSLContext sslContext = SSLContext.getInstance("TLS");
trustManagers = new TrustManager[]{ trustAll };
hostnameVerifier = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) { return true; }
};
} else if (sslCaCert != null) {
char[] password = null; // Any password will work.
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
KeyStore caKeyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = "ca" + Integer.toString(index++);
caKeyStore.setCertificateEntry(certificateAlias, certificate);
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(caKeyStore);
trustManagers = trustManagerFactory.getTrustManagers();
}
if (keyManagers != null || trustManagers != null) {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
httpClient.setSslSocketFactory(sslContext.getSocketFactory());
} else {
httpClient.setSslSocketFactory(null);
}
httpClient.setHostnameVerifier(hostnameVerifier);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
The solution was rather simple, there is attribute that swagger offers that took care of my issue.
ApiClient apiClient = new ApiClient();
apiClient.setBasePath("https://localhost:8077/api");
apiClient.setVerifyingSsl(false);

How to bypass ssl certificate checking in java

I want access a SOAP webservice url having https hosted in a remote vm. I am getting an exception while accessing it using HttpURLConnection.
Here's my code:
import javax.net.ssl.*;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* Created by prasantabiswas on 07/03/17.
*/
public class Main
{
public static void main(String [] args)
{
try
{
URL url = new URL("https://myhost:8913/myservice/service?wsdl");
HttpURLConnection http = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
} else {
http = (HttpURLConnection) url.openConnection();
}
String SOAPAction="";
// http.setRequestProperty("Content-Length", String.valueOf(b.length));
http.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
http.setRequestProperty("SOAPAction", SOAPAction);
http.setRequestMethod("GET");
http.setDoOutput(true);
http.setDoInput(true);
OutputStream out = http.getOutputStream();
}
catch (Exception e)
{
e.printStackTrace();
}
}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException
{
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'm getting the following exception:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1283)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1258)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
at Main.main(Main.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints
at sun.security.ssl.AbstractTrustManagerWrapper.checkAlgorithmConstraints(SSLContextImpl.java:1055)
at sun.security.ssl.AbstractTrustManagerWrapper.checkAdditionalTrust(SSLContextImpl.java:981)
at sun.security.ssl.AbstractTrustManagerWrapper.checkServerTrusted(SSLContextImpl.java:923)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
... 18 more
Tried different solution from the google search, Non of them worked. I want to avoid using keytool because I will be running my tests on different vm.
Does anyone have any solution for this?
Using X509ExtendedTrustManager instead of X509TrustManager() solved the problem. Here's the example:
public void trustAllHosts()
{
try
{
TrustManager[] trustAllCerts = new TrustManager[]{
new X509ExtendedTrustManager()
{
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return null;
}
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
}
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] xcs, String string, Socket socket) throws CertificateException
{
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] xcs, String string, Socket socket) throws CertificateException
{
}
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException
{
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException
{
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier()
{
#Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
catch (Exception e)
{
log.error("Error occurred",e);
}
}
Edit : Understand the vulnerability this would cause before using it. This is by no means recommended for production use.
The best way is to create a dummy trustmanager that trusts everything.
TrustManager[] dummyTrustManager = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
Then use the dummy trustmanager to initialize the SSL Context
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, dummyTrustManager, new java.security.SecureRandom());
Finally use the SSLContext to open connection
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
URL url = new URL("https://myhost:8913/myservice/service?wsdl");
This question has already been answered here in more detail
Java: Overriding function to disable SSL certificate check
Update:
Above issue is due to certificate signature algorithm not being supported by Java. As per this post, later releases of Java 8 have disabled md5 algorithm.
To enable md5 support, locate java.security file under <jre_home>/lib/security
and locate the line (535)
jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024,
and remove MD5
Try with Apache HTTP client, this works for me.
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
// GET or POST request with the client
...
Instead of using HttpsURLConnection.setDefaultSSLSocketFactory and your own implementation of TrustManager or X509ExtendedTrustManager, you can use TrustManagerFactory with a KeyStore with the certificate that issued the certificate you need to trust (for a self-signed certificate, this is the same as the host certificate) and call HttpsURLConnection.setSSLSocketFactory on the specific instance. This is both less code and avoids the security problems with trusting all HTTPS certicates.
In main:
if (url.getProtocol().toLowerCase().equals("https")) {
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setSSLSocketFactory(createSSLSocketFactory());
http = https;
}
The method createSSLSocketFactory looks like this:
private static SSLSocketFactory createSSLSocketFactory() {
File crtFile = new File("server.crt");
Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(crtFile));
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("server", certificate);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
return sslContext.getSocketFactory();
}

SSL client is validating the server certificate and I don't know why

I have a 2 way SSL client and I don't know why the client is validating the server certificate.
I added a TrustManager and in the getAcceptedIssuers method I placed a certificate that has nothing to do with the servers certificate. It seems that whatever I write in this method the server is validated.
This is my code:
// Create a key store and add private key and certificate that the client will use for authentication
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null, null);
keyStore.setKeyEntry("client", getPKFromFile("clientPrivateKey.pem"), "1234567".toCharArray(), new java.security.cert.Certificate[] { getX509CertificateFromFile("clientCertificate.pem"), getX509CertificateFromFile("intermediateCertificate.pem"), getX509CertificateFromFile("rootCertificate.pem")});
// Create the trust manager
final TrustManager[] trustCerts = new TrustManager[] { new X509TrustManager() {
#Override
public void checkClientTrusted( final X509Certificate[] chain, final String authType ) {
}
#Override
public void checkServerTrusted( final X509Certificate[] chain, final String authType ) {
}
#Override
public X509Certificate[] getAcceptedIssuers() {
try {
X509Certificate[] certs = new X509Certificate[1];
// add a certificate that has nothing to do with the server certificate
String DigiSignQualifiedPublicCA_FilePath = System.getProperty("DigiSignQualifiedPublicCA", "./sslstore/DigiSignQualifiedPublicCA.cer");
File DigiSignQualifiedPublicCA_File = new File(DigiSignQualifiedPublicCA_FilePath);
certs[0] = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(DigiSignQualifiedPublicCA_File));
return certs;
} catch (Exception ex) {
Logger.getLogger(Axis2ServerTest.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
} };
SSLContext sslCtx = SSLContext.getInstance("TLSv1.2");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, "1234567".toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
sslCtx.init(keyManagers, trustCerts, null);
HelloPojoStub stub = new HelloPojoStub("https://localhost/axis2/services/HelloPojo?wsdl");
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CUSTOM_PROTOCOL‌​_HANDLER, new Protocol("https",(ProtocolSocketFactory)new SSLProtocolSocketFactory(sslCtx),443));

Soap SSL handshake

My client is successfully getting response from server through HTTP.
SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
SOAPConnection connection = sfc.createConnection();
SOAPMessage soapMessageResponse = connection.call(soapRequest, new URL(serviceLocation));
I want SSL communication between client/server.
In another project I am successfully creating SSLSocketFactory from a KeyStore and TrustManagerFactory for SSL handshake.
How can I use SSLSocketFactory code in webservice client to make client SSL communication successful to call server.
I'm pretty sure it will use the default SSLContext. You can change that with SSLContext.setDefault().
SSLContext c = SSLContext.getInstance("SSL");
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(yourKeystore);
TrustManager tm = tmf.getTrustManagers()[0];
tm.
c.init(null, tm, null);
Here are some other values for the string parameters above.
If you need more complete control, you can implement your own subclass of SSLContext which returns your own implementation of SSLSocketFactory and set that SSLContext as the default:
public class MySSLContext extends SSLContext {
private SSLContext wrapped;
private SSLSocketFactory mySocketFactory;
public MySSLContext(SSLContext toWrap, SSLSocketFactory mySocketFactory) {
wrapped = toWrap;
this.mySocketFactory = mySocketFactory;
}
public SSLSocketFactory getSocketFactory() {
return mySocketFactory;
}
public SSLSessionContext getClientSessionContext() {
return wrapped;
}
// other delegates
}
Hi if you add this code your webservice class ı think your problem will be solve .
`
//just put it your somewhere
public static class miTM implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
// CAll This function in your webservice class .
private static void trustAllHttpsCertificates() throws Exception {
// Create a trust manager that does not validate certificate chains:
javax.net.ssl.TrustManager[] trustAllCerts =
new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc =
javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(
sc.getSocketFactory());
}
This line of code will not work in case of SSL.
SOAPMessage soapMessageResponse = connection.call(soapRequest, new URL(serviceLocation));
Create trustmanager and keymanagers from here.
In order to get response through SSL from axis2 webservice you need to open streams like given here

SSL/TLS error ("no cipher suites in common") with Netty when trying to establish a secure connection between a frontend and a backend

I want to secure a TCP connection between a backend and a frontend. We use Netty to establish a TCP connection which works pretty well. Now, we want to secure this connection by using SSL/TLS. For that reason I created a certificate request:
openssl req -newkey rsa:2048 -keyout key.pem -out request.pem -subj '/C=DE/O=XX/ST=XX/L=XX/O=XX/OU=XX/CN=someaddress.de/emailAddress=support#xxx.de'
The certificate was then created by the CA.
The keystore was created with:
keytool -import -alias xxx -keystore xxx.keystore -file cert-xxx.pem
Server with Netty at the backend:
public StatefulTcpServer(MessageHandler messageHandler, int port, KeyStore keyStore, String keyStorePassword) {
this.messageHandler = messageHandler;
factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
allChannels = new DefaultChannelGroup("clients");
initTLS(keyStore, keyStorePassword);
ServerBootstrap bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
#Override
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = Channels.pipeline();
if (sslContext != null) {
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(false);
sslEngine.setEnabledCipherSuites(new String[] {
"TLS_RSA_WITH_AES_128_CBC_SHA"
});
pipeline.addLast("ssl", new SslHandler(sslEngine));
}
pipeline.addLast("compressor", new ZlibEncoder());
pipeline.addLast("decompressor", new ZlibDecoder());
pipeline.addLast("decoder", new JBossSerializationDecoder());
pipeline.addLast("encoder", new JBossSerializationEncoder());
pipeline.addLast("handler", StatefulTcpServer.this);
return pipeline;
}
});
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.bind(new InetSocketAddress(port));
}
private void initTLS(KeyStore keyStore, String keyStorePassword) {
try {
if (keyStore != null) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, keyStorePassword.toCharArray());
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
}
}
catch (GeneralSecurityException e) {
logger.error("TLS connection could not be established", e);
sslContext = null;
}
}
Server with Netty in the frontend:
public void init(String backendHost, int backendPort, int timeOutSecs, boolean useTLS,
boolean acceptOnlyTrustworthyCertsForTLS) throws ConnectionFailedException {
channelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
if (useTLS) {
initTLS(acceptOnlyTrustworthyCertsForTLS);
}
ClientBootstrap bootstrap = new ClientBootstrap(channelFactory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
#Override
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = Channels.pipeline();
if (sslContext != null) {
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(true);
sslEngine.setEnabledCipherSuites(new String[] {
"TLS_RSA_WITH_AES_128_CBC_SHA"
});
pipeline.addLast("ssl", new SslHandler(sslEngine));
}
pipeline.addLast("compressor", new ZlibEncoder());
pipeline.addLast("decompressor", new ZlibDecoder());
pipeline.addLast("decoder", new JBossSerializationDecoder());
pipeline.addLast("encoder", new JBossSerializationEncoder());
pipeline.addLast("handler", StatefulTcpBackendCommunicator.this);
return pipeline;
}
});
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("keepAlive", true);
channelFuture = bootstrap.connect(new InetSocketAddress(backendHost, backendPort));
try {
boolean connected = channelFuture.await(timeOutSecs * 1000);
if (!connected || !channelFuture.isSuccess()) {
throw new ConnectionFailedException();
}
}
catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
private void initTLS(boolean acceptOnlyTrustworthyCertsForTLS) {
try {
TrustManager[] trustManagers;
if (acceptOnlyTrustworthyCertsForTLS) {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory
.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
trustManagers = trustManagerFactory.getTrustManagers();
}
else {
trustManagers = new TrustManager[] {
new X509TrustManager() {
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
#Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
return;
}
#Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
return;
}
}
};
}
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, new SecureRandom());
}
catch (GeneralSecurityException e) {
logger.error("TLS connection could not be established. TLS is not used!", e);
sslContext = null;
}
}
When trying to establish the connection between frontend and backend I get an exception:
javax.net.ssl.SSLHandshakeException: no cipher suites in common
This post was unfortunately not helpful. Is there something wrong with the configuration of the servers? Or do I use the wrong certificate type?

Categories

Resources