PKIX path building failed, but the certificate is in cacerts - java

I have the problem that is also described here.
The thing is that I created a certificate and added it to the keystore of tomcat, and then I copied it to the cacerts truststore. However, somehow I still get this error.
What I have done:
1) keytool -genkey -alias cas -keyalg RSA -keystore cas.keystore
-storepass changeit
2) keytool -exportcert -alias cas -file cas.crt -keystore cas.keystore
Step 2) because I wanted to put the certificate in my tomcat keystore and cacerts
3) keytool -import -alias cas -file cas.crt -keystore "C:\Program
Files\Java\jdk1.8.0_77\jre\lib\security\cacerts"
4) keytool -import -alias cas -file "C:\Program
Files\Java\jdk1.8.0_7\jre\bin\cas.crt" -keystore
"D:\portal\apache-tomcat-8.0.3\conf\portal.keystore"
So now with step 3 and 4 I added the certificate in my tomcat keystore and the truststore cacerts.
Now I can list my trust- and keystore
With this command..
keytool -list -v -keystore "C:\Program
Files\Java\jdk1.8.0_77\jre\lib\security\cacerts" -alias cas
... I get this:
Keystore-Kennwort eingeben:
Aliasname: cas
Erstellungsdatum: 09.09.2016
Eintragstyp: trustedCertEntry
Eigentümer: CN=xxx, OU=xxx, O=xxx, L=xxx, ST=xxx, C=xxx
Aussteller: CN=xxx, OU=xxx, O=xxx, L=xxx, ST=xxx, C=xxx
Seriennummer: xxx
Gültig von: Fri Sep 09 10:40:55 CEST 2016 bis: Thu Dec 08 09:40:55 CET 2016
Zertifikat-Fingerprints:
MD5: ....
SHA1: ....
SHA256: ....
Signaturalgorithmusname: SHA256withRSA
Version: 3
Erweiterungen:
#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [...
]
]
And with this:
keytool -list -v -keystore
"D:\portal\apache-tomcat-8.0.30\conf\portal.keystore" -alias cas
I get this:
Keystore-Kennwort eingeben:
Keystore-Typ: JKS
Keystore-Provider: SUN
Keystore enthält 1 Eintrag
Aliasname: cas
Erstellungsdatum: 09.09.2016
Eintragstyp: trustedCertEntry
Eigentümer: CN=xxx, OU=xxx, O=xxx, L=xxx, ST=xxx, C=xxx
Aussteller: CN=xxx, OU=xxx, O=xxx, L=xxx, ST=xxx, C=xxx
Seriennummer: ...
Gültig von: Fri Sep 09 10:40:55 CEST 2016 bis: Thu Dec 08 09:40:55 CET 2016
Zertifikat-Fingerprints:
MD5: ...
SHA1: ...
SHA256: ...
Signaturalgorithmusname: SHA256withRSA
Version: 3
Erweiterungen:
#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
]
]
If it is not clear: the certificates (cas) are the same.
So my impression was that the certificate is now in the keystore of the tomcat server and the truststore cacerts. But somehow I still get this exception when I entered my credentials on the CAS server and get redirected (full stacktrace bellow):
HTTP Status 500 - 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
These are my connectors in my tomcats server.xml:
<Connector port="8743" protocol="org.apache.coyote.http11.Http11Protocol" SSLEnabled="true"
maxThreads="150" scheme="https" keystoreFile="${catalina.base}/conf/portal.keystore" keystorePass="changeit"
secure="true" connectionTimeout="240000"
clientAuth="false" sslProtocol="TLS" allowUnsafeLegacyRenegotiation="true" />
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8309" protocol="AJP/1.3" redirectPort="8743" />
What is the possible cause of my problem? All the other threads like the one mentioned in the beginning point out that the OP did not import the certificate to the cacerts file, but I did.
The full stacktrace:
09-Sep-2016 12:05:30.146 SEVERE [http-bio-8743-exec-4] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [default] in context with path [/cas-sample] threw exception
java.lang.RuntimeException: 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 org.jasig.cas.client.util.CommonUtils.getResponseFromServer(CommonUtils.java:443)
at org.jasig.cas.client.validation.AbstractCasProtocolUrlBasedTicketValidator.retrieveResponseFromServer(AbstractCasProtocolUrlBasedTicketValidator.java:41)
at org.jasig.cas.client.validation.AbstractUrlBasedTicketValidator.validate(AbstractUrlBasedTicketValidator.java:193)
at org.jasig.cas.client.validation.AbstractTicketValidationFilter.doFilter(AbstractTicketValidationFilter.java:204)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:279)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
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 sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1513)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at org.jasig.cas.client.util.CommonUtils.getResponseFromServer(CommonUtils.java:429)
... 20 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:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
... 33 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)
... 39 more

My problem was quite unexpected. I had a Tomcat that had an modified setenv.bat that had options that pointed on another location of a keystore. I didn't know much about Tomcat and application servers in general so I couldn't figure that out earlier.

Your Connector element defines a keystore. That's a place where private keys and their certificates will be looked for.
Your exception concerns a truststore, which is a place where trusted CA certs are or are not found.
You need to define the truststore used by Tomcat somehow, either via configuration or via the javax.net.ssl.trustStore system property.

You can navigate to the tomcat/bin directory. Modify catalina.sh (or catalina.bat depending on your os).
Add the below properties to JAVA_OPTS.
JAVA_OPTS="$JAVA_OPTS -Djavax.net.ssl.trustStore=$CATALINA_HOME/certificates/truststore.ks -Djavax.net.ssl.trustStorePassword=truststorePassword -server"
I just recently had to fight through some truststore/keystore issues myself. A tool I found very helpful for easily viewing/modifying trust/keystores is keystore explorer.

Related

How to force client trusting in PKCS12 certificate(unable to find valid certification path to requested target)?

According the article:
I created PKCS12 certificate and put file keystore.p12 under the src/main/respurces
My spring boot application works fine and I have access to my rest services.
From another spring boot application I do http request:
ResponseEntity<byte[]> mappingTemplateResponseEntity = restTemplate.exchange(httpsUrl, HttpMethod.GET, new HttpEntity<>(new HttpHeaders()), byte[].class);
and this code lead to exception because certificate is not registered.
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://localhost:8801/stub_mapping_template": sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; 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 org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:666)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
at pack.MappingTemplateService.checkForUpdates(MappingTemplateService.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
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 sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:78)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:652)
... 17 common frames omitted
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:1491)
... 31 common frames omitted
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)
... 37 common frames omitted
According the article I tried to type:
D:\app\src\main\resources>keytool -list -v -storetype pkcs12
-keystore keystore.p12 Enter keystore password:
Keystore type: PKCS12 Keystore provider: SunJSSE
Your keystore contains 1 entry
Alias name: tomcat Creation date: Jan 9, 2018 Entry type:
PrivateKeyEntry Certificate chain length: 1 Certificate1: Owner:
CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown
Issuer: CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown,
C=Unknown Serial number: 64cd4d27 Valid from: Tue Jan 09 17:56:07 MSK
2018 until: Fri Jan 07 17:56:07 MSK 2028 Certificate fingerprints:
MD5: A6:F5:67:EE:87:65:21:62:50:5B:67:AE:63:F6:AE:C0
SHA1: B8:F5:F7:7D:8C:4C:90:0E:BA:CE:9D:22:3A:D3:A7:6E:BB:12:1B:D8
SHA256: 35:B5:DF:15:FC:3B:DD:D3:05:58:88:92:00:47:8F:62:2C:97:D7:20:77:FA:7D:55:00:64:E9:62:F4:7D:3B:08
Signature algorithm name: SHA256withRSA
Version: 3
Extensions:
1: ObjectId: 2.5.29.14 Criticality=false SubjectKeyIdentifier [ KeyIdentifier [ 0000: 3E D4 2D F8 AF D2 C2 4E 51 4F 3E A4 01 FE E2
34 >.-....NQO>....4 0010: 48 B0 5F 4F
H._O ] ]
looks like I should not export certificate explicitly because I use PKCS12 certificate.
How to fix my error?
I solved my issue:
Registered bean:
#Value("${http.client.ssl.trust-store}")
private Resource keyStore;
#Value("${http.client.ssl.trust-store-password}")
private String keyStorePassword;
#Bean
RestTemplate restTemplate() throws Exception {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(
keyStore.getURL(),
keyStorePassword.toCharArray()
).build();
SSLConnectionSocketFactory socketFactory =
new SSLConnectionSocketFactory(sslContext);
HttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(socketFactory).build();
HttpComponentsClientHttpRequestFactory factory =
new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(factory);
}
2.Added to application.properties:
# The format used for the keystore
server.ssl.key-store-type:PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore.p12
# The password used to generate the certificate
server.ssl.key-store-password=password
# The alias mapped to the certificate
server.ssl.key-alias=tomcat
http.client.ssl.trust-store=classpath:keystore.p12
http.client.ssl.trust-store-password=password

Tomcat 7 and invalid keystore format

I'm trying to connect to Tomcat through https on a remote server; I've found many answers, but no one has worked for me; I'm using Apache, Tomcat 7 on Ubuntu Server 14.04.
First, I created the certificate keystore writing:
keytool -genkey -alias tomcat -keyalg RSA
after I' ve edited "/etc/tomcat7/server.xml" to use ssl on port 8443:
<Connector port="8443" SSLEnabled="true"
protocol="org.apache.coyote.http11.Http11Protocol"
keystoreType="JKS"
maxThreads="150" scheme="https" secure="true"
keystoreFile="/usr/lib/jvm/java-7-openjdk-amd64/bin/keytool"
keystorePass="***********" keyAlias="tomcat"
clientAuth="false" sslProtocol="TLS"/>
where ********** is the password; restarting Tomcat through:
sudo service tomcat7 restart
I'm getting the following error in file "/var/log/tomcat7/catalina.out":
SEVERE: Failed to initialize connector [Connector[HTTP/1.1-8443]]
org.apache.catalina.LifecycleException: Failed to initialize component [Connector[HTTP/1.1-8443]]
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:106)
at org.apache.catalina.core.StandardService.initInternal(StandardService.java:559)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:813)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
at org.apache.catalina.startup.Catalina.load(Catalina.java:638)
at org.apache.catalina.startup.Catalina.load(Catalina.java:663)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:280)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:454)
Caused by: org.apache.catalina.LifecycleException: Protocol handler initialization failed
at org.apache.catalina.connector.Connector.initInternal(Connector.java:980)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
... 12 more
Caused by: java.io.IOException: Invalid keystore format
at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:650)
at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:55)
at java.security.KeyStore.load(KeyStore.java:1214)
at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getStore(JSSESocketFactory.java:392)
at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeystore(JSSESocketFactory.java:291)
at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:549)
at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:489)
at org.apache.tomcat.util.net.jsse.JSSESocketFactory.init(JSSESocketFactory.java:434)
at org.apache.tomcat.util.net.jsse.JSSESocketFactory.createSocket(JSSESocketFactory.java:181)
at org.apache.tomcat.util.net.JIoEndpoint.bind(JIoEndpoint.java:397)
at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:640)
at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:434)
at org.apache.coyote.http11.AbstractHttp11JsseProtocol.init(AbstractHttp11JsseProtocol.java:119)
at org.apache.catalina.connector.Connector.initInternal(Connector.java:978)
... 13 more
The keystore type is JKS, I've verified it through the command:
$JAVA_HOME/bin/keytool -list
which has returned:
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 1 entry
tomcat, 17-Oct-2015, PrivateKeyEntry,
Certificate fingerprint (SHA1): 33:14:32:DD:DA:20:BF:CF:70:32:F5:0E:E9:F1:C1:5B:4E:C3:DB:AB
where $JAVA_HOME is "/usr/lib/jvm/java-7-openjdk-amd64";
So when I try to connect to "https://myServerIp:8443/" or to "https://myDomainName:8443/" I get "Unable to connect" error.
just to further support this answer for beginners like me. On Windows OS
First go to C:\Program Files\Java\jdk1.8,
Press Shift + right-click to open command pront: write this keytool.exe -genkey -alias tomcat -keyalg RSA -keystore /{user.name}/.keystore,
A sequence of question will then follow after that you will see a new .keytore generated at the specify path
Now you need to go to server.xml and modify this two keystoreFile="${user.home}/.keystore" keystorePass="changeit" with the appropriate one.
Now it works correctly, in short:
I specified the path of the .keystore file
I configured Tomcat to use this file
Thanks to #Titus I've understood where the problem was: when I run the command
keytool -genkey -alias tomcat -keyalg RSA
or the command
$JAVA_HOME/bin/keytool -genkey -keyalg RSA -alias tomcat
the program keytool create a file .keystore in a folder of the server; the directory /usr/lib/jvm/java-7-openjdk-amd64/jre/bin contains a file named keystore, but this file is not correct to setup tomcat or for some reason it doesn't work in my case.
To specify the path of the file .keystore we can run the command
keytool -genkey -alias tomcat -keyalg RSA -keystore /path/.keystore
and after that I've configured Tomcat editing the file /etc/tomcat7/server.xml with the file just created:
<Connector port="8443" SSLEnabled="true"
protocol="org.apache.coyote.http11.Http11Protocol"
keystoreType="JKS"
maxThreads="150" scheme="https" secure="true"
keystoreFile="/path/.keystore"
keystorePass="************" keyAlias="tomcat"
clientAuth="false" sslProtocol="TLS"/>

OpenSSL certificate is giving 'Invalid keystore format' in tomcat 8

I am using tomcat 8 and need to make it SSL, So I use openSSL to generate self signed certificate and configured the same in tomcat's server.xml file. But I am getting the below exception
INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-7443"]
16-Apr-2015 09:50:56.647 SEVERE [main] org.apache.coyote.AbstractProtocol.init Failed to initialize end point associated with ProtocolHandler ["http-nio-7443"]
java.io.IOException: Invalid keystore format
at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:650)
at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:55)
at java.security.KeyStore.load(KeyStore.java:1433)
at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getStore(JSSESocketFactory.java:424)
at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeystore(JSSESocketFactory.java:323)
at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:581)
at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:521)
at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:363)
at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:730)
at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:457)
at org.apache.coyote.http11.AbstractHttp11JsseProtocol.init(AbstractHttp11JsseProtocol.java:120)
at org.apache.catalina.connector.Connector.initInternal(Connector.java:960)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
at org.apache.catalina.core.StandardService.initInternal(StandardService.java:567)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:851)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
at org.apache.catalina.startup.Catalina.load(Catalina.java:576)
at org.apache.catalina.startup.Catalina.load(Catalina.java:599)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
Write failed: Broken pipegMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43
That trace points to invalid format on your keystore.
Check this:
keytool -list -v -keystore keystore.jks
Are certificates listed in your keystore?
If you generated it with OpenSSL maybe you are generating a pkcs12 and if you import this and use a Connector on Tomcat without specifying the format, according to the default keyStoreType value, it's setted as "JKS".
https://tomcat.apache.org/tomcat-8.0-doc/config/http.html
keystoreType The type of keystore file to be used for the server
certificate. If not specified, the default value is "JKS".
Using keytool:
I suggest: try to generate the keystore with keytool (for me it's easier):
https://www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html?jn45301e6e=2
Generate a keystore and self-signed certificate:
keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048
Using PKCS12
Or if you pefer, you can also use a PKCS12 (if it's your case) with Tomcat:
Edit the JAVA_HOME/jre/lib/security/java.security file and change the default keystore type:
# Default keystore type.
keystore.type=pkcs12
Then configure your Connector with something similar to:
<!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
<Connector port="8443"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" disableUploadTimeout="true"
acceptCount="100" debug="0" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreType="PKCS12"
keystoreFile="yourKey.p12"
keystorePass="endeca"
truststoreType="PKCS12"
truststoreFile="yourKey.p12"
truststorePass="pass" />
In my case, openssl.exe which Tomcat recognized did not match with Tomcat Native Library(tcnative-1.dll).
I downloaded them from https://archive.apache.org/dist/tomcat/tomcat-connectors/native then ssl worked.

java.security.SignatureException: Signature does not match

I created a java keystore with name cloudsslkeystore.jks
keytool -genkeypair -validity 730 -alias cloudsslkey -keystore cloudsslkeystore.jks -dname "cn=localhost" -keypass password -storepass password
I exported it as certificate with name cloudcertificate.cer
keytool -export -rfc -keystore cloudsslkeystore.jks -alias cloudsslkey -file cloudcertificate.cer
Enter keystore password:password
Certificate stored in file <cloudcertificate.cer>
I added the certificate cloudcertificate.cer to my local java security folder
C:\Program Files\Java\jre7\lib\security>keytool -keystore cacerts -importcert -noprompt -trustcacerts -alias cloudsslkey -file cloudcertificate.cer
Enter keystore password:changeit
Certificate was added to keystore
Now I used the same java keystore cloudsslkeystore.jks in tomcat server of a different machine by modifying server.xml
<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" keystoreFile="c:\keytool\cloudsslkeystore.jks" keystorePass="password" />
When I try to hit a webservice thru a java client, I get this exception.
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Problem writing SAAJ model to stream: sun.security.validator.ValidatorException: PKIX
path validation failed: java.security.cert.CertPathValidatorException: signature check failed
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:159)
at com.sun.proxy.$Proxy39.getAllRecommendations(Unknown Source)
at client.WSClient.main(WSClient.java:73)
Caused by: com.ctc.wstx.exc.WstxIOException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValida
torException: signature check failed
at com.ctc.wstx.sw.BaseStreamWriter.writeCharacters(BaseStreamWriter.java:458)
at org.apache.cxf.staxutils.StaxUtils.copy(StaxUtils.java:749)
at org.apache.cxf.staxutils.StaxUtils.copy(StaxUtils.java:696)
at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor$SAAJOutEndingInterceptor.handleMessage(SAAJOutInterceptor.java:214)
at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor$SAAJOutEndingInterceptor.handleMessage(SAAJOutInterceptor.java:174)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:514)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:423)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:326)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:279)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:137)
... 2 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathVal
idatorException: signature check failed
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1884)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1091)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit$URLConnectionWrappedOutputStream.setupWrappedStream(URLConnectionHTTPConduit.java:17
4)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleHeadersTrustCaching(HTTPConduit.java:1302)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.onFirstWrite(HTTPConduit.java:1258)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit$URLConnectionWrappedOutputStream.onFirstWrite(URLConnectionHTTPConduit.java:201)
at org.apache.cxf.io.AbstractWrappedOutputStream.write(AbstractWrappedOutputStream.java:47)
at org.apache.cxf.io.AbstractThresholdOutputStream.unBuffer(AbstractThresholdOutputStream.java:89)
at org.apache.cxf.io.AbstractThresholdOutputStream.write(AbstractThresholdOutputStream.java:63)
at org.apache.cxf.io.CacheAndWriteOutputStream.write(CacheAndWriteOutputStream.java:80)
at org.apache.cxf.io.AbstractWrappedOutputStream.write(AbstractWrappedOutputStream.java:51)
at com.ctc.wstx.io.UTF8Writer.write(UTF8Writer.java:143)
at com.ctc.wstx.sw.BufferingXmlWriter.writeRaw(BufferingXmlWriter.java:285)
at com.ctc.wstx.sw.BufferingXmlWriter.writeCharacters(BufferingXmlWriter.java:603)
at com.ctc.wstx.sw.BaseStreamWriter.writeCharacters(BaseStreamWriter.java:456)
... 13 more
Caused by: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: signature check fail
ed
at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:350)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:260)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
... 37 more
Caused by: java.security.cert.CertPathValidatorException: signature check failed
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:159)
at sun.security.provider.certpath.PKIXCertPathValidator.doValidate(PKIXCertPathValidator.java:351)
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:191)
at java.security.cert.CertPathValidator.validate(CertPathValidator.java:279)
at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:345)
... 43 more
Caused by: java.security.SignatureException: Signature does not match.
at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:451)
at sun.security.provider.certpath.BasicChecker.verifySignature(BasicChecker.java:160)
at sun.security.provider.certpath.BasicChecker.check(BasicChecker.java:139)
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:133)
... 47 more
I finally found the problem:
The SignatureException does not indicate that the issuer is unknown to the client. In that case a CertPathBuilderException would be thrown.
The SignatureException was actually caused by not having the self-signed certificate imported as trusted certificate which must be done by the additional parameter -trustcacerts.
To answer the question why someone should want to trust a self signed certificate: The server is used for test purposes for automated client tests connecting to the server over HTTPS.
The Signature does not match error is the symptom that the server identity is unknown to the client, ie the client truststore does not have the server certificate.
Create the server certificate and add it to a keystore:
keytool -genkey -noprompt -alias "$alias" -dname "CN=$dname_cn, OU=$dname_ou, O=$dname_o, L=$dname_l, S=$dname_s, C=$dname_c" -keystore "$keystore" -storepass "$storepass" -keypass "$keypass"
and export it for the client into a truststore:
keytool -export -alias "$alias" -storepass "$storepass" -file "$alias".cer -keystore "$keystore"
If you want 2-way SSL then you have to repeat this twice, inverting, they both must know each other.
Now the tricky part is to build an SSLContext correctly and configure your client and server with it.
In Grizzly I do:
SSLContextConfigurator sslContextConfigurator = new SSLContextConfigurator();
// set up security context
sslContextConfigurator.setKeyStoreFile(configuration.getKeystore()); // contains the server keypair
sslContextConfigurator.setKeyStorePass(configuration.getKeystorePassword());
sslContextConfigurator.setKeyStoreType(configuration.getKeystoreType());
sslContextConfigurator.setKeyPass(configuration.getKeystoreKeypass());
sslContextConfigurator.setTrustStoreFile(configuration.getTruststore()); // contains the list of trusted certificates
sslContextConfigurator.setTrustStorePass(configuration.getTruststorePassword());
sslContextConfigurator.setTrustStoreType(configuration.getTruststoreType());
if (!sslContextConfigurator.validateConfiguration(true))
throw new Exception("Invalid SSL configuration");
For advanced debugging do not forget System.setProperty("javax.net.debug", "all");
-keypass password
Get rid of this parameter. The mechanism that supports javax.net.ssl.keyStore and javax.net.ssl.keyStorePassword doesn't support key passwords, only keystore passwords.

Unable to find valid certification path, jboss 5.1.0

When I am trying to invoke a SOAP webservice (.wsdl) that needs basic authentication over HTTPS from my local environment, I got the SSLHandShakeException.
First I have downloaded the certificate Cert.cer from the Chrome browser and followed the below steps.
1) keytool -genkey -dname "CN=localhost:8080, OU=Group Name, O=Company Name,L=City Name, S=State, C=IN" -alias "key_alias" -keyalg RSA -keypass changeit -keystore server.keystore
2) copy server.keystore C:\Work\jboss-5.1.0.GA\server\default\conf
3) keytool -export -alias "key_alias" -file Cert.cer -keystore C:\Work\jboss-5.1.0.GA\server\default\conf\server.keystore
4) copy Cert.cer C:\Work\jboss-5.1.0.GA\server\default\conf
5) keytool -printcert -v -file C:\Work\jboss-5.1.0.GA\server\default\conf\Cert.cer
6) keytool -import -alias "key_alias" -file Cert.cer -keystore "C:\Program Files (x86)\Java\jdk1.6.0_03\jre\lib\security\cacerts"
In C:\Work\jboss-5.1.0.GA\server\default\deploy\jbossweb.sar\server.xml
<!-- SSL/TLS Connector configuration using the admin devl guide keystore-->
<Connector name="https" protocol="HTTP/1.1" SSLEnabled="true"
port="8443" address="${jboss.bind.address}" keyAlias="key_alias"
scheme="https" secure="true" clientAuth="false"
keystoreFile="C:\Work\jboss-5.1.0.GA\server\default\conf\server.keystore"
keystorePass="changeit" sslProtocol = "TLS" />
After followed these steps, still I am facing the same exception as 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
2013-12-04 12:31:14,841 ERROR [STDERR] (http-127.0.0.1-8443-6) AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: 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
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace: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
what was the wrong in that? Could anyone helps me to find that??

Categories

Resources