I have simple Java client to MQTT Mosquitto server:
public class TestMQTT3 {
public static void main(String[] args) {
System.out.println("Starting");
String serverUrl = "ssl://192.168.1.8:8887";
String path= "C:\\projects\\certs\\CA4\\";
String caFilePath =path+"cacert.pem";
String mqttUserName = "b";
String mqttPassword = "b";
MqttClient client;
try {
client = new MqttClient(serverUrl, "2");
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(mqttUserName);
options.setPassword(mqttPassword.toCharArray());
options.setConnectionTimeout(60);
options.setKeepAliveInterval(60);
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
SSLSocketFactory socketFactory = getSocketFactory3(caFilePath);
options.setSocketFactory(socketFactory);
System.out.println("starting connect the server...");
client.connect(options);
System.out.println("connected!");
Thread.sleep(1000);
client.subscribe(
"/u/56ca327d17531d08e76bddd4a215e37f5fd6082f7442151c4d3f1d100a0ffd4e",
0);
client.disconnect();
System.out.println("disconnected!");
} catch (MqttException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private static SSLSocketFactory getSocketFactory3(final String caCrtFile) throws Exception
{
Security.addProvider(new BouncyCastleProvider());
// load CA certificate
X509Certificate caCert = null;
FileInputStream fis = new FileInputStream(caCrtFile);
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0)
{
caCert = (X509Certificate) cf.generateCertificate(bis);
System.out.println(caCert.toString());
}
// CA certificate is used to authenticate server
KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
caKs.load(null, null);
caKs.setCertificateEntry("ca-certificate", caCert);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(caKs);
// finally, create SSL socket factory
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(null, tmf.getTrustManagers(), null);
return context.getSocketFactory();
}
}
Trying to connect by using CA certificate:
Certificate:
Data:
Version: 3 (0x2)
Serial Number:
f6:7e:ef:1c:70:ef:30:64
Signature Algorithm: sha1WithRSAEncryption
Issuer: C=US, ST=California, L=Hawthorne, O=PhilNet, OU=UN, CN=CN
Validity
Not Before: Jan 15 17:36:08 2020 GMT
Not After : Jan 14 17:36:08 2021 GMT
Subject: C=US, ST=California, L=Hawthorne, O=PhilNet, OU=UN, CN=CN
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:d2:65:49:db:fc:87:dd:36:8a:e0:27:e6:bb:66:
66:78:35:af:86:ae:d3:e5:e2:07:db:8e:51:f2:67:
06:22:78:99:b3:2f:81:14:a9:e7:28:7e:2a:96:8d:
fb:ec:29:64:39:5b:b7:d4:3c:22:b0:30:18:0d:e4:
c1:38:57:c2:ba:c5:09:11:12:46:8b:cc:06:08:0d:
e4:86:3f:98:e7:61:2d:d8:a9:40:34:e6:87:d7:7d:
c4:7c:62:51:78:b3:fd:d8:a6:1d:15:0b:80:fb:78:
29:59:9c:b7:30:ad:7e:92:f0:bc:94:3c:03:30:c1:
83:28:92:de:34:0b:68:8c:19:6e:d7:29:de:75:23:
59:8c:11:51:a8:84:69:32:d3:96:3d:eb:df:44:7b:
b6:85:2e:f4:af:98:a7:28:84:7b:7d:c9:56:89:66:
e0:e0:3d:63:ae:59:46:23:98:13:bc:af:72:7b:6f:
d5:a6:ec:3e:4e:56:2c:87:f6:70:ab:47:05:a3:4a:
1b:9e:2c:ec:52:7f:3e:7f:b9:a3:33:59:8a:1d:28:
cc:d4:39:0c:8b:f2:12:2d:82:09:63:bd:ae:b3:51:
c6:a4:ac:d3:ab:e4:31:de:b6:b0:11:85:90:36:33:
70:15:94:d0:54:ab:07:bb:a9:6a:63:3e:84:cc:5c:
c3:13
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
X509v3 Subject Key Identifier:
75:AF:4E:B9:E0:49:FE:62:C1:21:28:B0:77:38:36:02:22:2E:1B:8F
X509v3 Authority Key Identifier:
keyid:75:AF:4E:B9:E0:49:FE:62:C1:21:28:B0:77:38:36:02:22:2E:1B:8F
X509v3 Subject Alternative Name:
IP Address:192.168.1.8, DNS:glass
Signature Algorithm: sha1WithRSAEncryption
7b:af:79:85:a6:69:3f:00:3c:d3:f9:b7:9f:f6:31:8a:3d:fd:
7f:9e:63:8b:86:de:4e:34:34:11:b3:e1:73:3d:24:8d:06:e5:
ba:a6:91:ba:bc:0a:2f:b1:95:34:4b:c8:cd:cf:6b:31:14:17:
5f:a4:4e:74:8d:07:01:fb:7f:2b:0d:fc:6a:35:85:46:ea:ba:
fc:98:92:de:69:4d:53:f2:c8:99:e9:bd:fa:df:a7:cf:aa:48:
c0:6f:93:ba:cd:79:43:8a:89:8b:e7:bd:99:dd:11:31:c8:5f:
76:a8:fd:99:13:1c:a0:8b:e3:86:72:62:cf:09:7c:de:9d:cf:
db:0b:fc:81:62:1c:32:b0:81:52:58:d9:2f:0b:44:fa:8a:59:
5f:23:b2:01:f0:8e:53:c3:8d:36:1c:25:0b:b5:80:67:95:85:
66:74:8a:08:cc:9c:dc:c1:c6:f6:4b:b7:4b:a3:1a:2d:41:19:
20:7b:54:f0:f1:fe:22:e6:55:7e:14:07:66:77:36:2c:17:ee:
31:33:40:c8:b9:6e:fa:c4:98:86:3a:6f:ba:c0:72:22:75:6c:
5f:4f:94:07:c9:cf:6d:67:61:ff:e9:da:88:95:68:72:78:43:
59:f2:e9:5b:0f:95:d6:7e:33:19:70:23:b4:1e:dd:c9:db:d4:
bc:16:d6:9e
Got error:
starting connect the server...
MqttException (0) - javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:736)
at java.lang.Thread.run(Thread.java:748)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:310)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1640)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:965)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
at org.eclipse.paho.client.mqttv3.internal.SSLNetworkModule.start(SSLNetworkModule.java:149)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:722)
... 1 more
Caused by: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:362)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:270)
at sun.security.validator.Validator.validate(Validator.java:262)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:330)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:237)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:132)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1622)
... 10 more
Caused by: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:159)
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:85)
at java.security.cert.CertPathValidator.validate(CertPathValidator.java:292)
at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:357)
... 16 more
What I do wrong and how to solve problem?
Related
In my app I use retrofit2(2.9.0) with OkHttp3(3.14.4). I want to add tls client certificate to all of my requests to some api. I've got the certificate in a .p12 file. I read the file, loaded into X509Certificate class then I used the .addTrustedCertificate(certificate) method. The certificate is correct I tried it using curl. Unfortunately when I run the code I get an exception.
Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:320)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:263)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:258)
at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:641)
at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:460)
at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:360)
at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392)
at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:443)
at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:421)
at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:177)
at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:164)
at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1152)
at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1063)
at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:402)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:336)
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:300)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:185)
at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.java:224)
at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.java:108)
at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.java:88)
at okhttp3.internal.connection.Transmitter.newExchange(Transmitter.java:169)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:41)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:94)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:88)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:213)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:229)
at okhttp3.RealCall.execute(RealCall.java:81)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:204)
at com.jakewharton.retrofit2.adapter.reactor.ExecuteSinkConsumer.accept(ExecuteSinkConsumer.java:39)
at com.jakewharton.retrofit2.adapter.reactor.ExecuteSinkConsumer.accept(ExecuteSinkConsumer.java:24)
at reactor.core.publisher.FluxCreate.subscribe(FluxCreate.java:94)
at reactor.core.publisher.Flux.subscribe(Flux.java:8143)
at com.jakewharton.retrofit2.adapter.reactor.BodyFlux.subscribe(BodyFlux.java:36)
at reactor.core.publisher.FluxSubscribeOn$SubscribeOnSubscriber.run(FluxSubscribeOn.java:194)
at reactor.core.scheduler.WorkerTask.call(WorkerTask.java:84)
at reactor.core.scheduler.WorkerTask.call(WorkerTask.java:37)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:290)
at java.base/sun.security.validator.Validator.validate(Validator.java:264)
at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:313)
at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:222)
at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129)
at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:625)
... 47 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
... 53 more
Process finished with exit code 1
my code looks like this
val fileName = "certyficate.p12"
val file = File(fileName)
val inputStream = file.inputStream()
val p12 = KeyStore.getInstance("pkcs12")
val password = "password"
p12.load(inputStream, password.toCharArray())
val alias = p12.aliases().nextElement()
val certificate = p12.getCertificate(alias) as X509Certificate
val ob = ObjectMapper().registerModule(KotlinModule())
val hostname = "https://myapi.com"
val timeout = 5L
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(timeout, TimeUnit.SECONDS)
.readTimeout(timeout, TimeUnit.SECONDS)
.writeTimeout(timeout, TimeUnit.SECONDS)
.apply {
addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
}
.apply {
val clientCertificate = HandshakeCertificates
.Builder()
.addTrustedCertificate(certificate)
.build()
sslSocketFactory(clientCertificate.sslSocketFactory(), clientCertificate.trustManager())
}
.build()
val retrofit = Retrofit.Builder()
.baseUrl(hostname)
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(
io.reactivex.schedulers.Schedulers.io()
))
.addCallAdapterFactory(ReactorCallAdapterFactory.createWithScheduler(Schedulers.newElastic(
MyApi::class.java.name
)))
.addConverterFactory(JacksonConverterFactory.create(ob))
.client(okHttpClient)
.build()
val p = retrofit.create(MyApi::class.java)
val res = p.doRequest().block()
println(res)
What's a possible reason? how to correctly use client certificates when using OkHttp3 ?
EDIT after I added .addPlatformTrustedCertificates() I get
Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131)
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:307)
at java.base/sun.security.ssl.Alert$AlertConsumer.consume(Alert.java:285)
at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:180)
at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:164)
at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1152)
at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1063)
at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:402)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:336)
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:300)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:185)
at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.java:224)
at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.java:108)
at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.java:88)
at okhttp3.internal.connection.Transmitter.newExchange(Transmitter.java:169)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:41)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:94)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:88)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:213)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:229)
at okhttp3.RealCall.execute(RealCall.java:81)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:204)
at com.jakewharton.retrofit2.adapter.reactor.ExecuteSinkConsumer.accept(ExecuteSinkConsumer.java:39)
at com.jakewharton.retrofit2.adapter.reactor.ExecuteSinkConsumer.accept(ExecuteSinkConsumer.java:24)
at reactor.core.publisher.FluxCreate.subscribe(FluxCreate.java:94)
at reactor.core.publisher.Flux.subscribe(Flux.java:8143)
at com.jakewharton.retrofit2.adapter.reactor.BodyFlux.subscribe(BodyFlux.java:36)
at reactor.core.publisher.FluxSubscribeOn$SubscribeOnSubscriber.run(FluxSubscribeOn.java:194)
at reactor.core.scheduler.WorkerTask.call(WorkerTask.java:84)
at reactor.core.scheduler.WorkerTask.call(WorkerTask.java:37)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
I run with javax.net.debug=ssl,handshake and found in my logs
javax.net.ssl|DEBUG|12|my.app.MyApi-2|2021-03-03 14:00:09.656 CET|CertificateMessage.java:290|No X.509 certificate for client authentication, use empty Certificate message instead
javax.net.ssl|DEBUG|12|my.app.MyApi-2|2021-03-03 14:00:09.656 CET|CertificateMessage.java:321|Produced client Certificate handshake message (
"Certificates": <empty list>
)
also my build.gradle
compile group: 'com.squareup.retrofit2', name: 'retrofit', version: '2.9.0'
compile group: 'com.squareup.retrofit2', name: 'converter-jackson', version: '2.9.0'
compile group: 'com.squareup.retrofit2', name: 'adapter-rxjava2', version: '2.9.0'
compile group: 'com.jakewharton.retrofit', name: 'retrofit2-reactor-adapter', version: '2.1.0'
compile group: 'com.squareup.okhttp3', name: 'okhttp-tls', version: '3.14.4'
val p12 = KeyStore.getInstance("pkcs12").apply {
load(inputStream, password)
}
val clientCert = p12.getCertificateChain(alias)[0] as X509Certificate
val rootCert = p12.getCertificateChain(alias)[1] as X509Certificate
val clientPrivateKey = p12.getKey(alias, password) as PrivateKey
val clientTLSCredentials = HeldCertificate(KeyPair(clientCert.publicKey, clientPrivateKey), clientCert)
val clientTlsHandShake = HandshakeCertificates.Builder()
.heldCertificate(clientTLSCredentials, rootCert)
.addPlatformTrustedCertificates()
.build()
val client = OkHttpClient.Builder()
.sslSocketFactory(clientTlsHandShake.sslSocketFactory(), clientTlsHandShake.trustManager())
.build()
This should be working, see for an example https://github.com/square/okhttp/blob/083315a473d8b2fc972a70449272b296683ac38c/android-test/src/androidTest/java/okhttp/android/test/letsencrypt/LetsEncryptClientTest.kt
val handshakeCertificates = HandshakeCertificates.Builder()
.addPlatformTrustedCertificates()
.addTrustedCertificate(cert)
.build()
clientBuilder
.sslSocketFactory(handshakeCertificates.sslSocketFactory(),
handshakeCertificates.trustManager)
You should can look at the certificate chain in SunCertPathBuilderException in a debugger.
This is a subclass of the generic CertPathBuilderException. It contains an adjacency list with information regarding the unsuccessful paths that the SunCertPathBuilder tried.
Ultimately you may need to enable SSL debugging in JSSE to see why it is failing.
Was able to get this working using Clyde Barrow's solution. Here is my pure Java solution (not much different than Clyde's). This is using a client certificate signed by Entrust and an intermediate certificate.
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(new File("myKeyStore.jks")), "mypassword".toCharArray());
Certificate[] certificates = keyStore.getCertificateChain("myalias");
X509Certificate clientCertificate = (X509Certificate) certificates[0];
X509Certificate intermediateCertificate = (X509Certificate) certificates[1];
PrivateKey privateKey = (PrivateKey) keyStore.getKey("myalias", "mypassword".toCharArray());
PublicKey publicKey = clientCertificate.getPublicKey();
KeyPair keyPair = new KeyPair(publicKey, privateKey);
HeldCertificate heldCertificate = new HeldCertificate(keyPair, clientCertificate);
HandshakeCertificates.Builder builder =
new HandshakeCertificates.Builder()
.heldCertificate(heldCertificate, intermediateCertificate)
.addPlatformTrustedCertificates();
HandshakeCertificates handshakeCertificates = builder.build();
OkHttpClient okClient =
new OkHttpClient().newBuilder().readTimeout(30, TimeUnit.SECONDS)
.sslSocketFactory(handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.build();
I try since many days to implement a TCPs communication between a Linux server and Windows/Linux client
The communication works but certificates exchanges doesn't, server is waiting for a client certificate which is never sent.
Client and server as booth running with OpenSSL 1.0.2n
Certificate is installed on Windows Store (.pfx)
Server Code :
void LoadCertificates(SSL_CTX* ctx, char* CertFile, char* KeyFile, char* CAFile)
{
// set the local certificate from CertFile
if (SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0)
{ ERR_print_errors_fp(stderr);abort(); }
// set the private key from KeyFile (may be the same as CertFile)
if (SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0)
{ ERR_print_errors_fp(stderr); abort(); }
// verify private key
if (!SSL_CTX_check_private_key(ctx))
{ printf(stderr, "Private key does not match the public certificate\n"); abort(); }
SSL_CTX_set_ecdh_auto(ctx, 1);
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
SSL_CTX_set_verify_depth(ctx,4);
if (SSL_CTX_load_verify_locations(ctx, CAFile, NULL) != 1)
{ printf("SSL_CTX_load_verify_locations failed\n"); ERR_print_errors_fp(stderr); }
}
void Servlet(SSL* ssl) /* Serve the connection -- threadable */
{ char buf[1024];
char reply[1024];
int sd, bytes;
const char* HTMLecho="<html><body><pre>%s</pre></body></html>\n\n";
if ( SSL_accept(ssl) == FAIL ) /* do SSL-protocol accept */
ERR_print_errors_fp(stderr);
else
{
bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
if ( bytes > 0 )
{
buf[bytes] = 0;
printf("Client msg: \"%s\"\n", buf);
sprintf(reply, HTMLecho, buf); /* construct reply */
SSL_write(ssl, reply, strlen(reply)); /* send reply */
}
else
ERR_print_errors_fp(stderr);
}
sd = SSL_get_fd(ssl); /* get socket connection */
SSL_free(ssl); /* release SSL state */
close(sd); /* close connection */
}
int main(int count, char *strings[])
{ SSL_CTX *ctx;
int server;
struct sockaddr_in addr;
char CertFile[] = "/opt/doamin.cer";char KeyFile[] = "/opt/doamin.key"; char CAFile[] = "doamin-ca.crt";
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
ctx = SSL_CTX_new(TLSv1_2_server_method());
SSL_CTX_set_options(ctx,SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_NO_COMPRESSION);
LoadCertificates(ctx, CertFile, KeyFile,CAFile); /* load certs */
server = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if ( bind(server, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
{ perror("can't bind port"); abort(); }
if ( listen(server, 10) != 0 )
{ perror("Can't configure listening port");abort();}
while (1)
{ struct sockaddr_in addr;
socklen_t len = sizeof(addr);
SSL *ssl;
int client = accept(server, (struct sockaddr*)&addr, &len); /* accept connection as usual */
printf("Connection: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
ssl = SSL_new(ctx); /* get new SSL state with context */
SSL_set_fd(ssl, client); /* set connection socket to SSL state */
Servlet(ssl); /* service connection */
}
close(server); /* close server socket */
SSL_CTX_free(ctx); /* release context */
}
Client side ( on Windows )
int main()
{
SSL_load_error_strings();
ERR_load_crypto_strings();
ERR_load_SSL_strings();
OpenSSL_add_all_algorithms();
(void)SSL_library_init();
char *hostname = "dct.sub.domain.fr"; int port = 445;
SSL_CTX *ctx = SSL_CTX_new(TLSv1_2_client_method()); /* Create new context */
if (ctx == NULL)
{ ERR_print_errors_fp(stderr);abort(); }
struct hostent *host = gethostbyname(hostname)
struct sockaddr_in addr;
char aszBuffer[256];
if (!host)
abort();
int server = socket(PF_INET, SOCK_STREAM, 0);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long*)(host->h_addr);
if (connect(server, (struct sockaddr *)&addr, sizeof(addr)) != 0)
{ closesocket(server);perror(hostname);abort();}
// Load certificate from windows Store
X509_STORE* pSt = SSL_CTX_get_cert_store(ctx);
X509_LOOKUP* m_lookup = X509_STORE_add_lookup(pSt, X509_LOOKUP_file());
{
HCERTSTORE hStore;
PCCERT_CONTEXT pContext = NULL;
X509 *x509;
hStore = CertOpenSystemStore(NULL, L"ROOT");
if (!hStore)
return 1;
LPTSTR pszString;
LPTSTR pszName;
DWORD cbSize;
CERT_BLOB blobEncodedName;
while (pContext = CertEnumCertificatesInStore(hStore, pContext))
{
if (!(cbSize = CertGetNameString(pContext,CERT_NAME_SIMPLE_DISPLAY_TYPE,0,NULL,NULL,0)))
MyHandleError(TEXT("CertGetName 1 failed."));
if (!(pszName = (LPTSTR)malloc(cbSize * sizeof(TCHAR))))
MyHandleError(TEXT("Memory allocation failed."));
if (CertGetNameString(pContext,CERT_NAME_SIMPLE_DISPLAY_TYPE,0,NULL,pszName,cbSize))
{
_tprintf(TEXT("\nSubject -> %s.\n"), pszName);
//-------------------------------------------------------
// Free the memory allocated for the string.
free(pszName);
}
x509 = NULL;
x509 = d2i_X509(NULL, (const unsigned char **)&pContext->pbCertEncoded, pContext->cbCertEncoded);
if (x509)
{
int i = X509_STORE_add_cert(pSt, x509);
if (i == 1)
printf("certificate added\n");
X509_free(x509);
}
}
CertFreeCertificateContext(pContext);
CertCloseStore(hStore, 0);
}
SSL_CTX_set_ecdh_auto(ctx, 1);
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, 0);
SSL_CTX_set0_chain_cert_store(ctx, pSt);
SSL* pSsl = SSL_new(ctx);
X509_VERIFY_PARAM *param = SSL_get0_param(pSsl);
X509_VERIFY_PARAM_set_hostflags(param, 0);
if (!X509_VERIFY_PARAM_set1_host(param, hostname, strlen(hostname) ))
return 0;
SSL_set_mode(pSsl, SSL_MODE_AUTO_RETRY);
SSL_set_fd(pSsl, server);
if (SSL_connect(pSsl) == -1)
abort();
long l = SSL_get_verify_result(pSsl);
if ( l == X509_V_OK)
printf("SSL_get_verify_result Ok \n");
else
printf("SSL_get_verify_result %d \n",l);
for (int j = 0; j < 5; ++j)
SSL_write(pSsl, 4, "test");
}
The client application gets to check the server but does not send its certificate ==> 1074894052:error:140890C7:SSL routines:ssl3_get_client_certificate:peer did not return a certificate:s3_srvr.c:3269:
Client result :
OpenSSL: Loaded CA cert : subject='/C=FR/O=compagny/CN=AC compagny Root'
OpenSSL: Loaded CA cert : subject='/C=FR/ST=France/L=Paris/O=compagny/OU=TRA/CN=*.sub.domain.fr' : ( From certmgr : With Private key for this domain )
OpenSSL: Loaded CA cert : subject='/C=FR/O=compagny/CN=AC compagny'
[...]
SSL_get_verify_result OK
Same thing appends with 'openssl s_client -connect dct.sub.domain.fr:445'
CONNECTED(000001A0)
depth=2 C = FR, O = company, OU = 0002 518888888, CN = AC company Root
verify error:num=19:self signed certificate in certificate chain
14220:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure: .\ssl\s3_pkt.c:1500:SSL alert number 40
14220:error:140790E5:SSL routines:ssl23_write:ssl handshake failure:.\ssl\s23_lib.c:177:
---
Certificate chain
0 s:/C=FR/ST=France/L=Paris/O=company/OU=TRA/CN=*.sub.domain.fr
i:/C=FR/O=company/OU=0002 999999999/CN=AC company
1 s:/C=FR/O=company/OU=0002 999999999/CN=AC company
i:/C=FR/O=company/OU=0002 518888888/CN=AC Ccompany
2 s:/C=FR/O=company/OU=0002 518888888/CN=AC company
i:/C=FR/O=company/OU=0002 518888888/CN=AC company
---
Server certificate
-----BEGIN CERTIFICATE-----
[...]
-----END CERTIFICATE-----
subject=/C=FR/ST=France/L=Paris/O=company/OU=TRA/CN=*.sub.domain.fr
issuer=/C=FR/O=company/OU=0002 999999999/CN=AC company
---
No client certificate CA names sent
Client Certificate Types: RSA sign, DSA sign, ECDSA sign
Requested Signature Algorithms: RSA+SHA512:DSA+SHA512:ECDSA+SHA512:RSA+SHA384:DSA+SHA384:ECDSA+SHA384:RSA+SHA256:DSA+SHA256:ECDSA+SHA256:RSA+SHA224:DSA+SHA224:ECDSA+SHA224:RSA+SHA1:DSA+SHA1:ECDSA+SHA1
Shared Requested Signature Algorithms: RSA+SHA512:DSA+SHA512:ECDSA+SHA512:RSA+SHA384:DSA+SHA384:ECDSA+SHA384:RSA+SHA256:DSA+SHA256:ECDSA+SHA256:RSA+SHA224:DSA+SHA224:ECDSA+SHA224:RSA+SHA1:DSA+SHA1:ECDSA+SHA1
Peer signing digest: SHA512
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 5325 bytes and written 138 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
Protocol : TLSv1.2
Cipher : ECDHE-RSA-AES256-GCM-SHA384
Session-ID:
Session-ID-ctx:
Master-Key: 8EB904862A6D7FB954F5A2AB701429D9D066852A0C7A40832EEC9AD3A56B66AE786D485BF8AFF8D37C4D27629A41D5F3
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
Start Time: 1523868440
Timeout : 300 (sec)
Verify return code: 19 (self signed certificate in certificate chain)
But works with : 'openssl.exe s_client -connect dct.sub.doamin.fr:445 -cert out.crt -key out.crt -CAfile out.crt'
CONNECTED(000001A0)
depth=2 C = FR, O = compagny, OU = 0002 999999999, CN = AC compagny Root
verify return:1
depth=1 C = FR, O = compagny, OU = 0002 998888888, CN = AC compagny
verify return:1
depth=0 C = FR, ST = France, L = Paris, O = compagny, OU = TRA, CN = *.sub.domain.fr
verify return:1
---
Certificate chain
0 s:/C=FR/ST=France/L=Paris/O=compagny/OU=TRA/CN=*.sub.domain.fr
i:/C=FR/O=compagny/OU=0002 998888888/CN=AC compagny
1 s:/C=FR/O=compagny/OU=0002 998888888/CN=AC compagny
i:/C=FR/O=compagny/OU=0002 999999999/CN=AC compagny Root
2 s:/C=FR/O=compagny/OU=0002 999999999/CN=AC compagny Root
i:/C=FR/O=compagny/OU=0002 999999999/CN=AC compagny Root
---
Server certificate
-----BEGIN CERTIFICATE-----
[...]
-----END CERTIFICATE-----
subject=/C=FR/ST=France/L=Paris/O=compagny/OU=TRA/CN=*.sub.doamin.fr
issuer=/C=FR/O=compagny/OU=0002 88888888/CN=AC compagny
---
No client certificate CA names sent
Client Certificate Types: RSA sign, DSA sign, ECDSA sign
Requested Signature Algorithms: RSA+SHA512:DSA+SHA512:ECDSA+SHA512:RSA+SHA384:DSA+SHA384:ECDSA+SHA384:RSA+SHA256:DSA+SHA256:ECDSA+SHA256:RSA+SHA224:DSA+SHA224:ECDSA+SHA224:RSA+SHA1:DSA+SHA1:ECDSA+SHA1
Shared Requested Signature Algorithms: RSA+SHA512:DSA+SHA512:ECDSA+SHA512:RSA+SHA384:DSA+SHA384:ECDSA+SHA384:RSA+SHA256:DSA+SHA256:ECDSA+SHA256:RSA+SHA224:DSA+SHA224:ECDSA+SHA224:RSA+SHA1:DSA+SHA1:ECDSA+SHA1
Peer signing digest: SHA512
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 7208 bytes and written 5569 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
Protocol : TLSv1.2
Cipher : ECDHE-RSA-AES256-GCM-SHA384
Session-ID: FBF6E85A99787BFEA2088948841E03EFABD831D1D809CEB21DCB2C7CF3710997
Session-ID-ctx:
Master-Key: 16C1400E26554260B5921C305382BBFC098915CEBE54F5F9BB58D29715AFF94F7EDC5F88432887E4A8EA8487C8D9E939
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 7200 (seconds)
TLS session ticket:
[...]
Start Time: 1523882730
Timeout : 300 (sec)
Verify return code: 0 (ok)
Any help is appreciate, I tried many things but now I don't know where to continue,
For this question I have prepared a test project WssEmbedded, which listens for incoming WebSocket connections at localhost:8080 and localhost:8443.
In the MyHandler class I create 2 connectors for this purpose:
public class MyHandler extends WebSocketHandler {
#Override
public void configure(WebSocketServletFactory factory) {
factory.register(MyListener.class);
}
public static void main(String[] args) throws Exception {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath("keystore.jks");
sslContextFactory.setKeyStorePassword("OBF:1l1a1s3g1yf41xtv20731xtn1yf21s3m1kxs");
Server server = new Server();
server.setHandler(new MyHandler());
ServerConnector wsConnector = new ServerConnector(server);
wsConnector.setHost("127.0.0.1");
wsConnector.setPort(8080);
server.addConnector(wsConnector);
ServerConnector wssConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()));
wssConnector.setHost("127.0.0.1");
wssConnector.setPort(8443);
server.addConnector(wssConnector);
server.start();
server.join();
}
}
I have added a key/certificate pair to keystore.jks with:
keytool -genkey -alias key1 -keyalg RSA -keypass password1 -keystore keystore.jks -storepass password1
The server starts without problems:
2016-06-22 13:34:45.254:INFO::main: Logging initialized #641ms
2016-06-22 13:34:45.404:INFO:oejs.Server:main: jetty-9.3.9.v20160517
2016-06-22 13:34:45.544:INFO:oejs.AbstractConnector:main: Started ServerConnector#3b354e17{HTTP/1.1,[http/1.1]}{127.0.0.1:8080}
2016-06-22 13:34:45.594:INFO:oejus.SslContextFactory:main: x509=X509#64d2d351(key1,h=[],w=[]) for SslContextFactory#1b68b9a4(file:///C:/Users/user1/jetty-newbie/WssEmbedded/keystore.jks,null)
2016-06-22 13:34:46.084:INFO:oejs.AbstractConnector:main: Started ServerConnector#1e53a15{SSL,[ssl]}{127.0.0.1:8443}
2016-06-22 13:34:46.084:INFO:oejs.Server:main: Started #1476ms
Then I have prepared a simple WssClient project for testing the above server:
public static void main(String[] args) {
final String WS_URL = "ws://127.0.0.1:8080";
MyListener socket = new MyListener("Hello world");
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(true);
WebSocketClient client = new WebSocketClient(sslContextFactory);
try {
client.start();
URI uri = new URI(WS_URL);
ClientUpgradeRequest cur = new ClientUpgradeRequest();
client.connect(socket, uri, cur);
socket.awaitClose(5, TimeUnit.SECONDS);
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
client.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The client works well and prints:
2016-06-22 13:36:06.130:INFO::main: Logging initialized #205ms
onWebSocketConnect: /127.0.0.1:8080
REQUEST:
Hello world
RESPONSE:
Hello /127.0.0.1:58518
onWebSocketClose: 1000 null
The server works well and prints:
2016-06-22 13:35:54.057:INFO:daw.MyListener:qtp1597462040-19: onWebSocketConnect: /127.0.0.1:58511
2016-06-22 13:35:54.097:INFO:daw.MyListener:qtp1597462040-14: onWebSocketText: Hello world
2016-06-22 13:35:54.107:INFO:daw.MyListener:qtp1597462040-13: onWebSocketClose: 1000 - null
However, when I change to WS_URL = "wss://127.0.0.1:8443" then it fails with:
2016-06-22 13:36:29.063:INFO::main: Logging initialized #208ms
onWebSocketError: java.nio.channels.ClosedChannelException
What have I missed here please? How to debug this?
UPDATE:
Thinking that the problem could be the self-signed certificate used above, I have taken a Thawte certificate valid for 3 years for my web domains slova.de and www.slova.de (they point to different IP addresses!) and imported it on CentOS 7 Linux into keystore using Oracle jdk1.8.0_91-1.8.0_91-fcs.x86_64:
# keytool -importcert -file /etc/pki/tls/certs/slova.de.crt -keystore keystore.jks -storepass password1
Owner: CN=slova.de
Issuer: CN=thawte DV SSL SHA256 CA, OU=Domain Validated SSL, O="thawte, Inc.", C=US
Serial number: 9354a665699cafbfa7875490d5a9894
Valid from: Mon Apr 04 02:00:00 CEST 2016 until: Fri Apr 05 01:59:59 CEST 2019
Certificate fingerprints:
MD5: 33:BB:62:8A:09:24:11:0F:C9:40:AA:68:F4:CD:2A:B7
SHA1: 52:E2:B6:79:55:F4:FE:05:0D:2E:7C:18:78:58:22:16:ED:28:4F:B6
SHA256: A3:D3:83:4E:99:01:BF:AE:FB:EB:59:40:23:74:1D:28:93:4B:20:15:1D:E1:AC:1A:97:31:C6:0C:9B:E1:2D:03
Signature algorithm name: SHA256withRSA
Version: 3
As you can see, I have now a trusted certificate there:
# keytool -list -keystore keystore.jks -storepass password1
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 2 entries
key1, Jun 22, 2016, PrivateKeyEntry,
Certificate fingerprint (SHA1): 8F:7D:8E:E0:8F:9E:39:A1:0C:23:D3:FF:4B:47:F5:0D:BA:EC:EE:F3
mykey, Jun 22, 2016, trustedCertEntry,
Certificate fingerprint (SHA1): 52:E2:B6:79:55:F4:FE:05:0D:2E:7C:18:78:58:22:16:ED:28:4F:B6
Then I have started the WssEmbedded program at the www.slova.de:8443 (at my Linux server it is different IP address from slova.de on which Apache is running):
# java -classpath $CPATHS de.afarber.wssembedded.MyHandler 144.76.184.154:8443
2016-06-22 19:45:21.093:INFO::main: Logging initialized #73ms
2016-06-22 19:45:21.144:INFO:oejs.Server:main: jetty-9.3.9.v20160517
2016-06-22 19:45:21.167:INFO:oejs.AbstractConnector:main: Started ServerConnector#6a38e57f{HTTP/1.1,[http/1.1]}{www.slova.de:8080}
2016-06-22 19:45:21.188:INFO:oejus.SslContextFactory:main: x509=X509#7a46a697(key1,h=[],w=[]) for SslContextFactory#5f205aa(file:///usr/share/java/words/keystore.jks,null)
2016-06-22 19:45:21.189:INFO:oejus.SslContextFactory:main: x509=X509#6d86b085(mykey,h=[slova.de, www.slova.de],w=[]) for SslContextFactory#5f205aa(file:///usr/share/java/words/keystore.jks,null)
2016-06-22 19:45:21.327:INFO:oejs.AbstractConnector:main: Started ServerConnector#71bbf57e{SSL,[ssl]}{www.slova.de:8443}
2016-06-22 19:45:21.327:INFO:oejs.Server:main: Started #309ms
And then I have run WssClient against wss://www.slova.de:8443 in NetBeans at my Macbook:
Executing command line: /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java -Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=56634 -classpath /Users/afarber/src/jetty-newbie/WssClient/target/classes:/Users/afarber/.m2/repository/org/eclipse/jetty/websocket/websocket-client/9.3.9.v20160517/websocket-client-9.3.9.v20160517.jar:/Users/afarber/.m2/repository/org/eclipse/jetty/jetty-util/9.3.9.v20160517/jetty-util-9.3.9.v20160517.jar:/Users/afarber/.m2/repository/org/eclipse/jetty/jetty-io/9.3.9.v20160517/jetty-io-9.3.9.v20160517.jar:/Users/afarber/.m2/repository/org/eclipse/jetty/websocket/websocket-common/9.3.9.v20160517/websocket-common-9.3.9.v20160517.jar:/Users/afarber/.m2/repository/org/eclipse/jetty/websocket/websocket-api/9.3.9.v20160517/websocket-api-9.3.9.v20160517.jar de.afarber.wssclient.Main
2016-06-22 19:45:31.718:INFO::main: Logging initialized #325ms
onWebSocketError: java.nio.channels.ClosedChannelException
(Nothing changed at the WssEmbedded server output).
Please help, how to get WSS working with embedded Jetty 9?
After adding -Dorg.eclipse.jetty.LEVEL=DEBUG -Djavax.net.debug=ssl friendly folks at the Jetty mailing list have pointed out, that there were NPEs at the server side caused by missing HttpConnectionFactory.
I have missed to copy that part from the embedded/LikeJettyXML example.
The following code in wssembedded/MyHandler.java works better:
public static void main(String[] args) throws Exception {
Server server = new Server();
server.setHandler(new MyHandler());
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(8443);
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath("keystore.jks");
sslContextFactory.setKeyStorePassword("OBF:1vn21ugu1saj1v9i1v941sar1ugw1vo0");
ServerConnector wsConnector = new ServerConnector(server);
wsConnector.setHost("localhost");
wsConnector.setPort(8080);
server.addConnector(wsConnector);
ServerConnector wssConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory,
HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(https_config)); // THIS WAS MISSING
wssConnector.setHost("localhost");
wssConnector.setPort(8443);
server.addConnector(wssConnector);
server.start();
server.join();
}
I am trying to call an API using SSL Certificates. From -Djavax.net.debug = all log I am passing the following steps.
Received "Server Hello Done"
Client Key Exchange: RSA PreMasterSecret, TLSv1
Received Finished Status on Client Key Exchange
Change Cipher Spec: Fail
RECV TLSv1 ALERT:
fatal,
handshake_failure
%% Invalidated: [Session-1, SSL_RSA_WITH_RC4_128_MD5]
I am using JDK1.7, with JCE Unlimited Strength Policy files. Thanks for you help.
EDIT: Between Server Hello Done and Client Key Exchange
*** ServerHelloDone
[read] MD5 and SHA1 hashes: len = 4
0000: 0E 00 00 00 ....
*** Certificate chain
*** ClientKeyExchange, RSA PreMasterSecret, TLSv1
Code for setting up SSL Socket Factory:
System.setProperty('javax.net.ssl.keyStore', 'jksfile')
System.setProperty('javax.net.ssl.keyStorePassword', '')
System.setProperty("https.protocols", "TLSv1");
System.setProperty('javax.net.ssl.trustStore', 'C:/Program Files/Java/jdk1.7.0_79/jre/lib/security/cacerts')
System.setProperty('javax.net.ssl.trustStorePassword', '')
SSLContext sslcontext = SSLContext.getInstance("TLSv1");
sslcontext.init(null, null, null);
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
if (conn instanceof HttpsURLConnection){
conn.setSSLSocketFactory(sslcontext.getSocketFactory());
}
Very simple question. I'm trying to us OpenSSL in Ruby to connect to a service, but getting errors.
When I use the following command:
openssl s_client -ssl3 -showcerts -connect example.com:443 -tls1 -cipher 'DHE-RSA-AES256-SHA' -nbio_test -state
It works great! The cert shows up with all the correct information.
But when I do:
openssl s_client -ssl3 -showcerts -connect example.com:13902 -tls1 -cipher 'DHE-RSA-AES256-SHA' -nbio_test -state
I get the following errors:
CONNECTED(00000003)
SSL_connect:before/connect initialization
SSL_connect:error in SSLv3 write client hello B
write W BLOCK
SSL_connect:SSLv3 write client hello B
SSL3 alert read:fatal:handshake failure
SSL_connect:failed in SSLv3 read server hello A
140735228511072:error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure:s3_pkt.c:1275:SSL alert number 40
140735228511072:error:1409E0E5:SSL routines:SSL3_WRITE_BYTES:ssl handshake failure:s3_pkt.c:598:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 7 bytes and written 0 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
SSL-Session:
Protocol : TLSv1
Cipher : 0000
Session-ID:
Session-ID-ctx:
Master-Key:
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
Start Time: 1408456884
Timeout : 7200 (sec)
Verify return code: 0 (ok)
---
The only thing that changed between the two commands is the port. The other flags were copied directly from the successful request. In other words I first did openssl s_client -showcerts -connect example.com:443 and then copied the ssl version, tls version, and cipher into the second two commands.
Is this a problem with openssl or the certificate? And if it is a problem with the certificate, how do I fix it? (and what is it?)
PS. I was able to connect in Java just fine using the following code, but still have to find a Ruby way:
public static void main(String[] args) throws NoSuchAlgorithmException,
KeyManagementException, IOException {
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) {
}
} };
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
URL url = new URL("https://example.com:13902");
URLConnection con = url.openConnection();
final Reader reader = new InputStreamReader(con.getInputStream());
final BufferedReader br = new BufferedReader(reader);
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
Figured it out. Was specifying both tls1 and ssl3. Needed to just specify tls1. Thanks Aria!