How create okhttp with ssl certificate - java

I have created 2 classes:
-This one extend OkHttp and have a new method getUnsafeOkHttpClient().
public class GetExampleOkHttp extends OkHttpClient {
public OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws CertificateException {
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
} };
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory);
builder.hostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
And other Main class:
class ExampleOkHttpMain
public static void main(String[] args) throws IOException {
GetExampleOkHttp example = new GetExampleOkHttp();
example.getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url("https://lachuzhnikov.kiev.ua/test.txt")
.build();
Response response = example.newCall(request).execute();
System.out.println(response.body().string());
}
}
But I still have an error:
Exception in thread "main" 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
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)

1: Download https://sourceforge.net/projects/portecle/
2: Open firefox and go to page and export cer
3: Backup Java\jdk....\jre\lib\security\cacerts (eg: C:\Program Files\Java\jdk1.7.0_79\jre\lib\security)
4: Copy cacerts to another folder
5: Portecle open file cacerts (pass: changeit) import cer in step 2 and save
6: Copy and replace new cacerts Java\jdk....\jre\lib\security\cacerts

Related

Ignore trusted certificate

I found some "standard code" from forums allowing me to skip the validation of trusted certificates in Java.
My code implements some old style WSDL client implementation. I'm using JDK 1.8.
public class myClass exteds Service{
public SessionProxy(String baseurl, SSLSocketFactory sslFactory, boolean compression) {
// Get the port
port = super.getPort(new QName("http://host.com/d3s/jel/dk/service/something/v2u1.wsdl", "Port"), Port.class);
// Set the endpoint address
Map<String, Object> context = ((BindingProvider) port).getRequestContext();
if (baseurl != null) {
context.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, baseurl);
}
SSLTool.disableCertificateValidation();
if (sslFactory != null) {
context.put(JAXWSProperties.SSL_SOCKET_FACTORY, sslFactory);
}
}
public String recordSessions(CasinoGameSessions sessions) throws
SystemFaultException, UserFaultException {
String result= "";
result += port.recordSessions(sessions) + "\n";
disposeSSLSocketFactory();
return result;
}
This is the SSLTool class I found (many other code samples are really similar to this one):
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
public class SSLTool {
public static void disableCertificateValidation() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}};
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) { return true; }
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Exception e) {}
}
}
When I run my code, despite the fact I call SSLTool.disableCertificationValidation() I get the exception:
aused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ~[?:1.8.0_162]
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154) ~[?:1.8.0_162]
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:2038) ~[?:1.8.0_162]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1135) ~[?:1.8.0_162]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385) ~[?:1.8.0_162]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413) ~[?:1.8.0_162]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397) ~[?:1.8.0_162]
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[?:1.8.0_162]
at sun.net.www.protocol.https.AbstractDelegateHttpsUR
This should mean my client still tries to validate the server certificate and to make the handshake with it.

javax.net.ssl.SSLHandshakeException: Handshake failed in Android 7.0

I am calling API to login but I am getting error of ssl handshake in Android 7.0, other than this version everything is working fine. I am using retrofit.
Following is the error.
SSL handshake terminated: ssl=0xcbcd0340: Failure in SSL library, usually a protocol error
error:1000043e:SSL routines:OPENSSL_internal:TLSV1_ALERT_INAPPROPRIATE_FALLBACK (external/boringssl/src/ssl/s3_pkt.c:610 0xebc87640:0x00000001)
Also as said by someone to add the following code so that this issue will be resolved but still no luck,
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.cipherSuites(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
.build();
okHttpClient.connectionSpecs(Collections.singletonList(spec));
I have even tried to letgo trust each and every certificate but still no luck. Following is the code.
public static OkHttpClient.Builder sslSocketFactory(OkHttpClient.Builder okHttpClient)
{
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_0)
.allEnabledCipherSuites()
.build();
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
//////// OkHttpClient.Builder builder = new OkHttpClient.Builder();
okHttpClient.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
okHttpClient.hostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Following are my ssllabs tested using android 7.0
ssllabs test
In all other android versions all API's are working fine I do get response, but I am not able to get response in version 7.0.
Actually it's more likely to be a ssl_ciphers server-side settings problem.
Assuming nginx, change your ssl_ciphers settings to the one recommended by openHab :
ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:HIGH:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!CBC:!EDH:!kEDH:!PSK:!SRP:!kECDH;
Don't forget to reload (systemctl reload nginx) and now all problematic android devices should work just fine.

Random javax.net.ssl.SSLExceptions using OkHttp client

In my android app am using a okhttp client which trusts all ssl certificates. The problem is, am facing random SSLExceptions. For example 8 out of 10 calls fail due to SSLExceptions and 2 succeed.
Any pointers on why this might be happening?
Please let me know if you need more info.
stack trace:
javax.net.ssl.SSLException: Connection closed by peer
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:405)
at com.squareup.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:103)
at com.squareup.okhttp.Connection.connect(Connection.java:143)
at com.squareup.okhttp.Connection.connectAndSetOwner(Connection.java:185)
at com.squareup.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
at com.squareup.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:341)
at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.squareup.okhttp.Call.getResponse(Call.java:273)
at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:230)
at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:201)
at com.squareup.okhttp.Call.execute(Call.java:81)
at retrofit.client.OkClient.execute(OkClient.java:53)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:326)
at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)
at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at retrofit.Platform$Android$2$1.run(Platform.java:142)
at java.lang.Thread.run(Thread.java:841)
This is how i create the okHttp client:
private OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
return createOkHttpClientWithTimeout(sslSocketFactory);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected OkHttpClient createOkHttpClientWithTimeout(SSLSocketFactory sslSocketFactory) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
okHttpClient.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
okHttpClient.setSslSocketFactory(sslSocketFactory);
okHttpClient.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return okHttpClient;
}
Note: I know that trusting all SSL certificates is bad.

openid4java YadisException peer not authenticated error

I am writing a Java JSP code that authenthicates against a WSO2 IS server using openid. I have taken the example code from de developer so I get the following:
<%
ConsumerManager manager = new ConsumerManager ();
String _returnURL = "https://192.168.15.48:9443/ficlient/secret.jsp";
List discoveries = manager.discover("https://myserverIP/openid");
DiscoveryInformation discovered = manager.associate(discoveries);
session.setAttribute("discovered", discovered);
AuthRequest authReq = manager.authenticate(discovered, _returnURL);
nextlink = authReq.getDestinationUrl(true);
%>
Secret data
On the 3rd line (List discoveries...) I get an exception:
org.openid4java.discovery.yadis.YadisException: 0x704: I/O transport error: peer not authenticated
I have understood that this is due to a non valid ssl certificate issued for the https comunication and have tried including the following (as found on Internet), to avoid the verification:
<%
// 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( java.security.cert.X509Certificate[] certs, String authType) {}
public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) {}
}
};
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (Exception e) {}
%>
But it is still not working. What have I missed?
I finally solved it by using Oltu libraries for authenthication.

Setting trust store programatically in ActiveMQSslConnectionFactory seems to fail

I have been working on a java activemq client software to connect to a ssl powered broker, but setting the trust store programatically through:
// Configure the secure connection factory.
ActiveMQSslConnectionFactory connectionFactory = new ActiveMQSslConnectionFactory(url);
connectionFactory.setTrustStore("/conf/client.ts"); // truststore which includes the certificate of the broaker
connectionFactory.setTrustStorePassword("password");
as indicated here. However, that throw a
javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building failed
Error
Following the response of the QA Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error? I was able to successfully connect the client to the broker by adding the broker certificate to my java installation's trusted certificates.
However, in this case, I do not want each user using the application to import the certificate on their java distribution, but rather that the client application already carries the broker certificate. How can I do that preferably using the ActiveMQSslConnectionFactory class?
From what I understand, you need to trust all the incoming self-signed certificates.
You could try this way (create a trust-manager which does not validate and then register it:
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certificates, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certificates, String authType) {
}
}
};
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
} catch (GeneralSecurityException e) {
}
//then do the ssl conversation.
I still havent managed to set the truststore programattically using the setTrustStore method from ActiveMQSslConnectionFactory
But based on #Chris response, it was possible to attach a new trust manager which accept all certificates to the ActiveMQSslConnectionFactory.
In order to do so, I created the same TrustManager as him, but used a different method to link it to the ActiveMQSslConnectionFactory
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certificates, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certificates, String authType) {
}
}
};
try {
String connectionString = "ssl://ipaddress:port"
ActiveMQSslConnectionFactory factory = new ActiveMQSslConnectionFactory(connectionString);
factory.setKeyAndTrustManagers(null, trustAllCerts, new SecureRandom());
Connection connection = factory.createConnection(user,password);
connection.start();
} catch (Exception e) {
}

Categories