Apache Camel Keystore Jetty Proxy - java

I'm building an application for my work and came across an issue I don't know quite how to solve. We're creating a Camel Jetty Proxy that is supposed to connect to an HTTPS website. We got the proxy up for non-secure sites easily, but now we're running into issues with connecting to a secure website with Camel and Jetty.
org.apache.camel.CamelExchangeException: JettyClient failed cause by: General SSLEngine problem. Exchange[ID-jasonm-win7-53769-1497563726897-0-1]. Caused by: [javax.net.ssl.SSLHandshakeException - General SSLEngine problem]
at org.apache.camel.component.jetty9.JettyContentExchange9.doTaskCompleted(JettyContentExchange9.java:164)
at org.apache.camel.component.jetty9.JettyContentExchange9.onConnectionFailed(JettyContentExchange9.java:130)
at org.apache.camel.component.jetty9.JettyContentExchange9$1.onFailure(JettyContentExchange9.java:225)
at org.eclipse.jetty.client.RequestNotifier.notifyFailure(RequestNotifier.java:253)
at org.eclipse.jetty.client.RequestNotifier.notifyFailure(RequestNotifier.java:239)
at org.eclipse.jetty.client.HttpSender.abort(HttpSender.java:541)
at org.eclipse.jetty.client.HttpSender.anyToFailure(HttpSender.java:342)
at org.eclipse.jetty.client.HttpSender$CommitCallback.failed(HttpSender.java:706)
at org.eclipse.jetty.client.http.HttpSenderOverHTTP$HeadersCallback.failed(HttpSenderOverHTTP.java:280)
at org.eclipse.jetty.io.WriteFlusher$PendingState.fail(WriteFlusher.java:260)
at org.eclipse.jetty.io.WriteFlusher.onFail(WriteFlusher.java:482)
at org.eclipse.jetty.io.AbstractEndPoint.close(AbstractEndPoint.java:120)
at org.eclipse.jetty.io.ssl.SslConnection$DecryptedEndPoint.close(SslConnection.java:974)
at org.eclipse.jetty.io.ssl.SslConnection$DecryptedEndPoint.fill(SslConnection.java:678)
at org.eclipse.jetty.client.http.HttpReceiverOverHTTP.process(HttpReceiverOverHTTP.java:114)
at org.eclipse.jetty.client.http.HttpReceiverOverHTTP.receive(HttpReceiverOverHTTP.java:70)
at org.eclipse.jetty.client.http.HttpChannelOverHTTP.receive(HttpChannelOverHTTP.java:90)
at org.eclipse.jetty.client.http.HttpConnectionOverHTTP.onFillable(HttpConnectionOverHTTP.java:115)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at org.eclipse.jetty.io.ssl.SslConnection.onFillable(SslConnection.java:202)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at sun.security.ssl.Handshaker.checkThrown(Handshaker.java:1364)
at sun.security.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:529)
at sun.security.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:807)
at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:775)
at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:624)
at org.eclipse.jetty.io.ssl.SslConnection$DecryptedEndPoint.fill(SslConnection.java:525)
... 16 more
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1708)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:303)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:295)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1369)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:156)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:925)
at sun.security.ssl.Handshaker$1.run(Handshaker.java:865)
at sun.security.ssl.Handshaker$1.run(Handshaker.java:862)
at java.security.AccessController.doPrivileged(Native Method)
at sun.security.ssl.Handshaker$DelegatedTask.run(Handshaker.java:1302)
at org.eclipse.jetty.io.ssl.SslConnection$DecryptedEndPoint.fill(SslConnection.java:630)
... 16 more
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 sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:281)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:136)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1356)
... 23 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 29 more
Upon review we found out that it's because we weren't accepting the certificate. So we found this code online that takes in the *.jks files and will allow for a secure connection
private void configureSslForJetty()
{
KeyStoreParameters ksp = new KeyStoreParameters();
ksp.setResource("c:\\Projects\\blah\\fakefilter.jks");
ksp.setPassword("123456");
KeyManagersParameters kmp = new KeyManagersParameters();
kmp.setKeyStore(ksp);
kmp.setKeyPassword("export-password");
SSLContextParameters scp = new SSLContextParameters();
scp.setKeyManagers(kmp);
JettyHttpComponent jettyComponent = getContext().getComponent("jetty", JettyHttpComponent.class);
jettyComponent.setSslContextParameters(scp);
}
private void configureSslForHttp4()
{
KeyStoreParameters trust_ksp = new KeyStoreParameters();
trust_ksp.setResource("c:\\Projects\\blah\\fakeca.jks");
trust_ksp.setPassword("123456");
TrustManagersParameters trustp = new TrustManagersParameters();
trustp.setKeyStore(trust_ksp);
SSLContextParameters scp = new SSLContextParameters();
scp.setTrustManagers(trustp);
HttpComponent httpComponent = getContext().getComponent("https4", HttpComponent.class);
httpComponent.setSslContextParameters(scp);
}
The problem that we're not understanding is that I don't know where the *.jks file is coming from OR where the passwords are coming from. Where does this information reside? Is there a relative path that I can follow to get the *.jks files?

By running javas keytool, you can insert the certificate into Java's Keystore which will solve the issue of not finding the certificates. There was no need for the Keystore code.
https://support2.microfocus.com/techdocs/2680.html

Related

Let's Encrypt + Hitch: Android OkHttp java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date

Hi and thank you for helping!
Very infrequently on our Android application, we get errors that start as java.security.cert.CertificateException: Chain validation failed with then traces to the exception of Response is unreliable: its validity interval is out-of-date. This impacts API calls and media playback (as ExoPlayer 2 uses okhttp).
We manage SSL transactions via Hitch, and acquire our certificates from Let's Encrypt. What's odd is that when this issue happens, the certificates still work fine on web, iOS tvOS, and Roku, but not on Android.
The error is intermittent, and in a matter of 24-48 hours, it seems this exception no longer happens. On okhttp I see StackOverflow articles where users suggest adding custom TrustManager class into okhttp that accepts all certificates, but I see that as insecure.
My question are how can I properly log what validity interval it's receiving, vs what it expects to have, and how can I tweak the settings at the Java level to trust beyond that window so that this exception doesn't happen?
For context, here is a stack trace affecting playback.
2019-10-21 16:42:51.883 31064-32727/com.sbs.lamusica.debug E/ExoPlayerImplInternal: Source error.
com.google.android.exoplayer2.upstream.HttpDataSource$HttpDataSourceException: Unable to connect to https://interstitials.lamusica.com/lamusica/black-video.mp4
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:194)
at com.google.android.exoplayer2.upstream.DefaultDataSource.open(DefaultDataSource.java:147)
at com.google.android.exoplayer2.source.ExtractorMediaPeriod$ExtractingLoadable.load(ExtractorMediaPeriod.java:841)
at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:308)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: javax.net.ssl.SSLHandshakeException: Chain validation failed
at com.android.org.conscrypt.ConscryptFileDescriptorSocket.startHandshake(ConscryptFileDescriptorSocket.java:236)
at com.android.okhttp.internal.io.RealConnection.connectTls(RealConnection.java:1480)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:1424)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:1368)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:219)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:142)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:104)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:392)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:325)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:470)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:26)
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:429)
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:350)
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:192)
at com.google.android.exoplayer2.upstream.DefaultDataSource.open(DefaultDataSource.java:147) 
at com.google.android.exoplayer2.source.ExtractorMediaPeriod$ExtractingLoadable.load(ExtractorMediaPeriod.java:841) 
at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:308) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:764) 
Caused by: java.security.cert.CertificateException: Chain validation failed
at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:719)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:543)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:564)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:632)
at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:499)
at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:422)
at com.android.org.conscrypt.TrustManagerImpl.getTrustedChainForServer(TrustManagerImpl.java:343)
at android.security.net.config.NetworkSecurityTrustManager.checkServerTrusted(NetworkSecurityTrustManager.java:94)
at android.security.net.config.RootTrustManager.checkServerTrusted(RootTrustManager.java:88)
at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:208)
at com.android.org.conscrypt.ConscryptFileDescriptorSocket.verifyCertificateChain(ConscryptFileDescriptorSocket.java:426)
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.NativeSsl.doHandshake(NativeSsl.java:383)
at com.android.org.conscrypt.ConscryptFileDescriptorSocket.startHandshake(ConscryptFileDescriptorSocket.java:231)
at com.android.okhttp.internal.io.RealConnection.connectTls(RealConnection.java:1480) 
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:1424) 
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:1368) 
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:219) 
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:142) 
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:104) 
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:392) 
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:325) 
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:470) 
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127) 
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89) 
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:26) 
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:429) 
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:350) 
at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:192) 
at com.google.android.exoplayer2.upstream.DefaultDataSource.open(DefaultDataSource.java:147) 
at com.google.android.exoplayer2.source.ExtractorMediaPeriod$ExtractingLoadable.load(ExtractorMediaPeriod.java:841) 
at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:308) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:764) 
Caused by: java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date
2019-10-21 16:42:51.886 31064-32727/com.sbs.lamusica.debug E/ExoPlayerImplInternal: at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:135)
at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:222)
at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:140)
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:79)
at com.android.org.conscrypt.DelegatingCertPathValidator.engineValidate(DelegatingCertPathValidator.java:44)
at java.security.cert.CertPathValidator.validate(CertPathValidator.java:301)
at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:715)
... 34 more
Caused by: java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date
at sun.security.provider.certpath.OCSPResponse.verify(OCSPResponse.java:619)
at sun.security.provider.certpath.RevocationChecker.checkOCSP(RevocationChecker.java:709)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:363)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:337)
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:125)
... 40 more
Suppressed: java.security.cert.CertPathValidatorException: Could not determine revocation status
at sun.security.provider.certpath.RevocationChecker.buildToNewKey(RevocationChecker.java:1092)
at sun.security.provider.certpath.RevocationChecker.verifyWithSeparateSigningKey(RevocationChecker.java:910)
at sun.security.provider.certpath.RevocationChecker.checkCRLs(RevocationChecker.java:577)
at sun.security.provider.certpath.RevocationChecker.checkCRLs(RevocationChecker.java:465)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:394)
Here is another example stacktrace affecting an API call.
javax.net.ssl.SSLHandshakeException: Chain validation failed
at com.android.org.conscrypt.ConscryptFileDescriptorSocket.startHandshake(ConscryptFileDescriptorSocket.java:236)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:320)
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:284)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:169)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:94)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:264)
at okhttp3.RealCall.execute(RealCall.java:93)
at com.sbs.lamusica.ui.fragment.home.HomePagerFragment.run(HomePagerFragment.java:200)
at com.sbs.lamusica.ui.fragment.home.HomePagerFragment$FetchLocationsList.doInBackground(HomePagerFragment.java:706)
at com.sbs.lamusica.ui.fragment.home.HomePagerFragment$FetchLocationsList.doInBackground(HomePagerFragment.java:693)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.security.cert.CertificateException: Chain validation failed
at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:719)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:543)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:564)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:632)
at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:499)
at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:422)
at com.android.org.conscrypt.TrustManagerImpl.getTrustedChainForServer(TrustManagerImpl.java:343)
at android.security.net.config.NetworkSecurityTrustManager.checkServerTrusted(NetworkSecurityTrustManager.java:94)
at android.security.net.config.RootTrustManager.checkServerTrusted(RootTrustManager.java:88)
at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:208)
at com.android.org.conscrypt.ConscryptFileDescriptorSocket.verifyCertificateChain(ConscryptFileDescriptorSocket.java:426)
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.NativeSsl.doHandshake(NativeSsl.java:383)
at com.android.org.conscrypt.ConscryptFileDescriptorSocket.startHandshake(ConscryptFileDescriptorSocket.java:231)
... 28 more
Caused by: java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:135)
at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:222)
at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:140)
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:79)
at com.android.org.conscrypt.DelegatingCertPathValidator.engineValidate(DelegatingCertPathValidator.java:44)
at java.security.cert.CertPathValidator.validate(CertPathValidator.java:301)
at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:715)
... 41 more
Caused by: java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date
at sun.security.provider.certpath.OCSPResponse.verify(OCSPResponse.java:619)
at sun.security.provider.certpath.RevocationChecker.checkOCSP(RevocationChecker.java:709)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:363)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:337)
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:125)
... 47 more
Suppressed: java.security.cert.CertPathValidatorException: Could not determine revocation status
at sun.security.provider.certpath.RevocationChecker.buildToNewKey(RevocationChecker.java:1092)
at sun.security.provider.certpath.RevocationChecker.verifyWithSeparateSigningKey(RevocationChecker.java:910)
at sun.security.provider.certpath.RevocationChecker.checkCRLs(RevocationChecker.java:577)
at sun.security.provider.certpath.RevocationChecker.checkCRLs(RevocationChecker.java:465)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:394)
... 49 more
2019-07-24 23:45:18.793 1473-3146/? V/WindowManager: Relayout Window{87d24e5 u0 com.sbs.lamusica.deb
Thanks for everyone's help!
After countless searching, I finally learned that hitch actually automatically manages the retrieval of OCSP staples and it can be configured to attach them.
After our app resurfaced with this issue just now at this obscene hour, I applied the following changes on my RedHat server:
Create a /var/lib/hitch-ocsp directory
Set the ownership of /var/lib/hitch-ocsp to the hitch user
Added the following two options to the /etc/hitch/hitch.conf
ocsp-dir = "/var/lib/hitch-ocsp"
ocsp-verify-staple = on
Ran service hitch restart to rerun hitch and now I started seeing OCSP stapling on my SSL responses whenever I ran it against https://entrust.ssllabs.com/analyze.html
So far immediately after the change I am now seeing our Android app properly trust these requests, but I'll post here if the issue resurfaces.
In my case, it was enough to just set the proper system time on the device.
('Settings' > 'System' > 'Date & Time' > 'Automatic date & time').

SSL connection error on valid certificate

I got an javax.net.ssl.SSLHandshakeException: Chain validation failed, when I´m trying to connect to my API server, the certificate is valid nowdays, and in the stack trace I got Caused by: java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date, the certificate is valid and it´s working on iOS and in the website, the problem is only in Android.
I´m using Retrofit, here is the clitent generation
fun generateClient(): OkHttpClient {
val client = OkHttpClient.Builder()
client.addInterceptor {
val request = it.request()
val url = request.url().newBuilder()
.build()
val newRequest = it.request().newBuilder().url(url).build()
it.proceed(newRequest)
}
client.connectTimeout(10, TimeUnit.SECONDS)
client.readTimeout(30, TimeUnit.SECONDS)
return client.build()
}
And the full trace is this
javax.net.ssl.SSLHandshakeException: Chain validation failed
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:361)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:302)
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:270)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:162)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at es.app.webservice.WebService$Companion$generateClient$1.intercept(WebService.kt:67)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:180)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:91)
at es.app.bd.cacheDb.databseRepositories.SplashActivityRepository$getVersions$1.invoke(SplashActivityRepository.kt:28)
at es.app.bd.cacheDb.databseRepositories.SplashActivityRepository$getVersions$1.invoke(SplashActivityRepository.kt:17)
at kotlin.concurrent.ThreadsKt$thread$thread$1.run(Thread.kt:30)
Caused by: java.security.cert.CertificateException: Chain validation failed
at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:788)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:612)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:633)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:678)
at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:499)
at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:422)
at com.android.org.conscrypt.TrustManagerImpl.getTrustedChainForServer(TrustManagerImpl.java:343)
at android.security.net.config.NetworkSecurityTrustManager.checkServerTrusted(NetworkSecurityTrustManager.java:94)
at android.security.net.config.RootTrustManager.checkServerTrusted(RootTrustManager.java:88)
at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:203)
at com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:607)
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:357)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:302) 
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:270) 
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:162) 
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257) 
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135) 
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114) 
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42) 
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93) 
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93) 
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126) 
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
at es.app.bd.cacheDb.webservice.WebService$Companion$generateClient$1.intercept(WebService.kt:67) 
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200) 
at okhttp3.RealCall.execute(RealCall.java:77) 
at retrofit2.OkHttpCall.execute(OkHttpCall.java:180) 
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:91) 
at es.app.bd.cacheDb.databseRepositories.SplashActivityRepository$getVersions$1.invoke(SplashActivityRepository.kt:28) 
at es.app.bd.cacheDb.databseRepositories.SplashActivityRepository$getVersions$1.invoke(SplashActivityRepository.kt:17) 
at kotlin.concurrent.ThreadsKt$thread$thread$1.run(Thread.kt:30) 
Caused by: java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date
E/AndroidRuntime: at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:133)
at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:225)
at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:143)
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:79)
at com.android.org.conscrypt.DelegatingCertPathValidator.engineValidate(DelegatingCertPathValidator.java:44)
at java.security.cert.CertPathValidator.validate(CertPathValidator.java:301)
at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:784)
... 39 more
Caused by: java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date
at sun.security.provider.certpath.OCSPResponse.verify(OCSPResponse.java:619)
at sun.security.provider.certpath.RevocationChecker.checkOCSP(RevocationChecker.java:709)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:363)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:337)
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:125)
... 45 more
Suppressed: java.security.cert.CertPathValidatorException: Could not determine revocation status
at sun.security.provider.certpath.RevocationChecker.buildToNewKey(RevocationChecker.java:1092)
at sun.security.provider.certpath.RevocationChecker.verifyWithSeparateSigningKey(RevocationChecker.java:910)
at sun.security.provider.certpath.RevocationChecker.checkCRLs(RevocationChecker.java:577)
at sun.security.provider.certpath.RevocationChecker.checkCRLs(RevocationChecker.java:465)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:394)
... 47 more
Update 1:
If I access the webpage from Chrome on the phone it works, but the app is still crashing.
In my case it was enought to just set proper system time on device ('Settings' > 'System' > 'Date & Time' > 'Automatic date & time').
Looking at line Suppressed: java.security.cert.CertPathValidatorException: Could not determine revocation status suggests that the failure occurs at the revocation validation step which relies on the OCSP Protocol.
What might happen here, is that your device is not connected to the internet and can't contact the authority server in order to check the validity of your certificate (it's only a guess).
If you don't want your application to have access to the authority server, you should activate "OCSP stappling" on your server. This means that your server is going to send the OCSP validation receipt as well as the certificate.
In my case, I had to add this sentence to AndroidManifest.xml:
android:usesCleartextTraffic="true"
as shown in context here:

Java JDBC Public Key connection failed with: "unable to find valid certification path to requested target" [duplicate]

This question already has answers here:
Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?
(33 answers)
Closed 5 years ago.
I would like to allow a connection from a java client.
This Java client needs to support multiple public keys for different DB's.
I must do it with a PUBLIC KEY and MUST NOT trust server certificate.
I have searched online but could not find a full solution for this problem, these are some of the links I have read:
first
second
third
I have also read this link myt question is not duplicate since its a completly different connection type - this is a JDBC connection with conneciton manager and not a general URL connection with SSL.
and many more, all the stack overflow solution I found offered to trust server certificate which means skip the public key verification
This is my code:
String connectionString = "jdbc:mysql://abcd-efg.rds.amazonaws.com:3306/test?trustServerCertificate=false&useSSL=true&requireSSL=true&verifyServerCertificate=true"
File f = new File("C:\\temp\\amazonPublic.pem");
CertificateFactory fact = null;
fact = CertificateFactory.getInstance("X.509");
X509Certificate cer = (X509Certificate) fact.generateCertificate(new FileInputStream(f));
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] password = new char[] {'1','2','3','4'};
ks.load(null, password);
ks.setCertificateEntry("alias", cer);
FileOutputStream fos = new FileOutputStream(new File("C:\\temp\\ca.cer"));
ks.store(fos, password);
fos.close();
Properties p = new Properties();
p.setProperty("javax.net.ssl.trustStore","C:\\temp\\ca.cer");
p.setProperty("javax.net.ssl.trustStorePassword","1234");
try (java.sql.Connection connection =
DriverManager.getConnection(connectionString,p)) {
connection.isValid(1000);
}
And this is the error:
Caused by: java.sql.SQLException: Could not connect to yyyyy-zz-prd-xxxxxxxxxxxx-1.rds.amazonaws.com:3306: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.handleConnectionPhases(AbstractConnectProtocol.java:706)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connect(AbstractConnectProtocol.java:406)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1022)
at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:483)
at org.mariadb.jdbc.Driver.connect(Driver.java:106)
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 sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
... 17 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 23 more
What am I missing in the solution?
For the sake of Humankind while working with MariaDB driver - debugging it
I find out that:
The property should be "serverSslCert" or "trustStore"
The prefix of javax.net.ssl only required when working with System.setProperty
So this simple change did the trick.
Properties p = new Properties();
p.setProperty("serverSslCert","C:/temp/amazonPublic.pem");
p.setProperty("trustStorePassword",jdbcDetails.getSensitiveData());
p.setProperty("user",jdbcDetails.username);
p.setProperty("password",jdbcDetails.getSensitiveData());

Can't connect to host by TLS with Vert.x

I am trying to connect to specific host with TLS support. I have a valid private key - "my.key" , my certificate - "my.crt", and also rootCA certificate "root_ca.crt". I already know that requested host using OpenSsl. Vertx may use some different variants how to do this:
By JksOptions() and java keystore file ".jks"
By PfxOptions() and file ".pfx" (in PKCS12 format)
By PemKeyCertOptions() and two files ("key.pem" and "cert.pem")
But when i doing like this:
NetClient client = vertx.createNetClient(
(NetClientOptions) new NetClientOptions()
.setLogActivity(true)
.setSsl(true)
.setOpenSslEngineOptions(new OpenSSLEngineOptions())
.addEnabledSecureTransportProtocol("TLSv1.2")
.setJksOptions(
new JksOptions()
.setPath("/path/to/my.jks")
.setPassword("password")
)
);
client.connect(some_port, "some_host", ar -> {
if (ar.succeeded()) {
LOG.debug("Connection succeeded!!!!");
} else {
LOG.debug("Connection failed!!!! :: {} :: {}", ar.cause(), ar.cause().getMessage());
}
});
build is success, but when i run this code i have exception:
INFO: Succeeded in deploying verticle
[vert.x-eventloop-thread-0] DEBUG io.netty.handler.ssl.ReferenceCountedOpenSslContext - verification of certificate failed
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.validator.PKIXValidator.doBuild(PKIXValidator.java:397)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:302)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:281)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:136)
at io.netty.handler.ssl.ReferenceCountedOpenSslClientContext$ExtendedTrustManagerVerifyCallback.verify(ReferenceCountedOpenSslClientContext.java:223)
at io.netty.handler.ssl.ReferenceCountedOpenSslContext$AbstractCertificateVerifier.verify(ReferenceCountedOpenSslContext.java:606)
at org.apache.tomcat.jni.SSL.readFromSSL(Native Method)
at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.readPlaintextData(ReferenceCountedOpenSslEngine.java:470)
at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:927)
at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1033)
at io.netty.handler.ssl.SslHandler$SslEngineType$1.unwrap(SslHandler.java:200)
at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1117)
at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1039)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:411)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:248)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:349)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:341)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:349)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:129)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:642)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:565)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:479)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:441)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
at java.lang.Thread.run(Thread.java:748)
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:392)
... 30 more
Maybe i am doing something wrong when creating the keystore?
To create it i am using this tutorial - https://support.adeptia.com/hc/en-us/articles/207878953-How-to-create-a-KeyStore-with-certificate-chain
Please help me understand how can i get correct keystore to connect with my host by TLS?
I find a way to create correct java keystore in PKCS12 format by this command:
openssl pkcs12 -inkey my.key -in my.crt -export -out domain.pfx
and then put generated "domain.pfx" file in PfxOptions and "root_ca.crt" file put in PemTrustOptions like this:
return new NetClientOptions()
.setSsl(true)
.addEnabledSecureTransportProtocol("TLSv1.2")
.setPfxKeyCertOptions(
new PfxOptions()
.setPath(pathToKeystoreFile)
.setPassword(keystorePassword)
)
.setPemTrustOptions(
new PemTrustOptions()
.addCertPath(rootCACertificate)
);
P.S. keystorePassword you entered while creating a certificates.

Using Javamail and Greenmail for SMTPS/SSL

I'm trying to write a test that will uses JavaMail SMTP or SMTPS to send a message via SSL and authentication to a Greenmail server that I'm running.
I've written a quick little sub that should do exactly what I'm wanting:
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import com.icegreen.greenmail.user.GreenMailUser;
import com.icegreen.greenmail.util.GreenMail;
public class MailTest {
public static void main(String[] args) throws Exception {
GreenMail greenmail = new GreenMail();
try {
greenmail.start();
String email = "foo#bar";
String userid = "user";
String password = "pa$$word";
GreenMailUser setUser = greenmail.setUser(email, userid, password);
setUser.create();
GreenMailUser user = greenmail.getManagers().getUserManager().getUser(userid);
System.out.println("User created:" + user.getEmail() + ":" + user.getLogin() + ":" + user.getPassword());
int portSmtps = greenmail.getSmtps().getPort();
System.out.println("Smtps started on port:" + portSmtps);
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.socketFactory.port", portSmtps);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getInstance(props);
Transport transport = session.getTransport("smtp");
transport.connect("localhost", portSmtps, userid, password);
System.out.println("Transport is connected: " + transport.isConnected());
} finally {
greenmail.stop();
}
}
}
My problem is that I get several exceptions:
Exception in thread "Thread-7" java.lang.RuntimeException: javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
at com.icegreen.greenmail.smtp.SmtpHandler.run(Unknown Source)
Caused by: javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1293)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:65)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at com.icegreen.greenmail.smtp.SmtpConnection.readLine(Unknown Source)
at com.icegreen.greenmail.smtp.SmtpHandler.handleCommand(Unknown Source)
... 1 more
Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:136)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1720)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:954)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:632)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:202)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:272)
at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:276)
at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:122)
at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:212)
at java.io.BufferedWriter.flush(BufferedWriter.java:236)
at java.io.PrintWriter.flush(PrintWriter.java:276)
at com.icegreen.greenmail.util.InternetPrintWriter.println(Unknown Source)
at com.icegreen.greenmail.util.InternetPrintWriter.println(Unknown Source)
at com.icegreen.greenmail.smtp.SmtpConnection.println(Unknown Source)
at com.icegreen.greenmail.smtp.SmtpHandler.sendGreetings(Unknown Source)
... 1 more
Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 3465;
nested exception is:
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 com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
at javax.mail.Service.connect(Service.java:295)
at MailTest.main(MailTest.java:35)
Caused by: 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 com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1649)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1206)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:136)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:893)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1165)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1149)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:507)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
... 3 more
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 sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:323)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217)
at sun.security.validator.Validator.validate(Validator.java:218)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1185)
... 13 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318)
... 19 more
I've tried looking at a few other answers here, but I must be missing something:
JavaMail to send secure email through vps - SSLHandshake Exception, PKIX path building failed, etc. - Can't send mail
PKIX path building failed: unable to find valid certification path to requested target
Using JavaMail with TLS
Sorry for the long post and thanks in advance for any advice.
You should start your GreenMail server like this:
Security.setProperty("ssl.SocketFactory.provider", DummySSLSocketFactory.class.getName());
GreenMail mailServer = new GreenMail(ServerSetupTest.SMTPS);
mailServer.start();
The SSL certificate used on the Greenmail server must be signed by a "known" certificate authority, OR you must add the CA certificate that was used to sign the cert to Java's keystore. There's no way to tell Java to not validate the certificate chain up to a known CA.
It also worked for me with JUNIT5:
#RegisterExtension
static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.POP3S.setVerbose(true));
#BeforeAll
static void setup() {
Security.setProperty("ssl.SocketFactory.provider", DummySSLSocketFactory.class.getName());
...
}

Categories

Resources