Java refusing certificate that browser accepts - java

I'm having trouble configuring a valid certificate (not self-signed!) in Wildfly 9. I have configured the HTTPS connector in Wildfly:
<https-listener name="https" socket-binding="https" security-realm="UndertowRealm" />
Security realm:
<security-realm name="UndertowRealm">
<server-identities>
<ssl>
<keystore path="domain.p12" relative-to="jboss.server.config.dir" keystore-password="password"
alias="appcert" />
</ssl>
</server-identities>
</security-realm>
And generated the keystore with this command:
openssl pkcs12 -export -in domain.crt -inkey domain.key -out domain.p12 -name appcert -CAfile cafile.crt -caname root
Now, when I open the application in the browser everything works fine. The browser recognizes the certificate as a valid certificate without prompting for an exception as it would in a self-signed certificate.
However, when I try to connect to the very same URL through SSLPoke.java, I get the following exception:
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.writeRecord(SSLSocketImpl.java:747)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
at SSLPoke.main(SSLPoke.java:26)
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)
... 9 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)
... 15 more
If I import the certificate in the client this error goes away, but I think I should not have to do this, since this is a valid certificate.
The test code is the following:
import java.io.InputStream;
import java.io.OutputStream;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
/** Establish a SSL connection to a host and port, writes a byte and
* prints the response. See
* http://confluence.atlassian.com/display/JIRA/Connecting+to+SSL+services
*/
public class SSLPoke {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: "+SSLPoke.class.getName()+" ");
System.exit(1);
}
try {
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(args[0], Integer.parseInt(args[1]));
InputStream in = sslsocket.getInputStream();
OutputStream out = sslsocket.getOutputStream();
// Write a test byte to get a reaction :)
out.write(1);
while (in.available() > 0) {
System.out.print(in.read());
}
System.out.println("Successfully connected");
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
Why is this happening, and what is the correct way to setup the SSL certificate?

The problem here is that Java by default comes with a very limited set of root CA certificates. It "accepts" far fewer CAs than a typical browser. The simplest way to solve the problem is to export a set of CA certificates from a browser like Chrome or Firefox and import them into Java's keystore using keytool.

It's happening because none of the certificates in the chain is trusted by the Java truststore.
The most general solution would be to import the top certificate (the last in the chain, the topmost signer) into the JRE's lib/security/cacerts file.

Related

Connect Java SSL Server to a Java SSL server [duplicate]

This question already has answers here:
"PKIX path building failed" and "unable to find valid certification path to requested target"
(54 answers)
Closed 4 years ago.
I'm having a hard time when trying to connect a java ssl server to another java ssl server. both of them running with the same ssl key.
This is what the first server looks like:
public HostServer() throws IOException {
System.setProperty("javax.net.ssl.keyStore", HOST_SERVER_KEY_FILE);
System.setProperty("javax.net.ssl.keyStorePassword", SSL_KEY_PASSWORD);
serverSocket = ((SSLServerSocketFactory) SSLServerSocketFactory.getDefault()).createServerSocket(HOST_SERVER_PORT);
System.out.println("Host server is running and waiting for clients to connect...");
connectedRequestServers = new ArrayList<ClientData>();
connectedRequestServersSemaphore = new Semaphore(1);
}
public void start() {
try {
while (true) {
Socket socket = serverSocket.accept();
Thread clientHandler = new Thread(new ClientHandler(socket));
clientHandler.start();
}
} catch (IOException ex) {
Logger.getLogger(HostServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
This is what the second server looks like:
public RequstServer() throws IOException, NoSuchAlgorithmException, KeyManagementException, GeneralSecurityException {
System.setProperty("javax.net.ssl.keyStore", HostServer.HOST_SERVER_KEY_FILE);// REQUST_SERVER_KEY_FILE);
System.setProperty("javax.net.ssl.keyStorePassword", HostServer.SSL_KEY_PASSWORD); //SSL_KEY_PASSWORD);
serverSocket = ((SSLServerSocketFactory) SSLServerSocketFactory.getDefault()).createServerSocket(REQUEST_SERVER_PORT);
System.out.println("Request Server is up and running!");
System.setProperty("javax.net.ssl.trustStore", HostServer.HOST_SERVER_KEY_FILE);
hostSocket = ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(HostServer.HOST_SERVER_ADDRESS, HostServer.HOST_SERVER_PORT);
os = new ObjectOutputStream(hostSocket.getOutputStream());
is = new ObjectInputStream(hostSocket.getInputStream());
}
The first server is running fine, but when ever i'm trying to run the second server, I get the follwing error, meaning that the connection to the first server has failed.
If anyone can help me I will be so happy!
Request Server is up and running!
3:12:47 PM Ver1.RequstServer main
SEVERE: null
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.writeRecord(SSLSocketImpl.java:747)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1877)
at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1786)
at java.io.ObjectOutputStream.<init>(ObjectOutputStream.java:247)
at Ver1.RequstServer.<init>(RequstServer.java:70)
at Ver1.RequstServer.main(RequstServer.java:38)
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)
... 12 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)
... 18 more
Server side:
System.setProperty("javax.net.ssl.trustStore", keyStore);
System.setProperty("javax.net.ssl.keyStore", keyStore);
System.setProperty("javax.net.ssl.keyStorePassword", keyStorePass);
SSLServerSocketFactory sslFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
serverSocket = (SSLServerSocket) sslFactory.createServerSocket(port, queueLength);
Socket clientConnection = socket.accept();
Client side:
System.setProperty("javax.net.ssl.trustStore", keyStore);
System.setProperty("javax.net.ssl.keyStore", keyStore);
System.setProperty("javax.net.ssl.keyStorePassword", keyStorePass);
SSLSocketFactory sslFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
socket = (SSLSocket) sslFactory.createSocket(address, port);
socket.startHandshake();
To generate keystores:
keytool -genkey -alias server -keyalg RSA -keystore server.jks
keytool -genkey -alias client -keyalg RSA -keystore client.jks
keytool -export -file server.cert -keystore server.jks -storepass 123456 -alias server
keytool -export -file client.cert -keystore client.jks -storepass 123456 -alias client
keytool -import -file client.cert -keystore server.jks -storepass 123456 -alias client
keytool -import -file server.cert -keystore client.jks -storepass 123456 -alias server

PKIX path building failed, but the certificate is in cacerts

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.

Cannot access Webservice under SSL from Java

I have a web service that runs under SSL using an SSL wildcard certificate that was signed by thawte. I can see the thumbprint for the thawte primary root cert in cacerts, however when I try to access my cert I get an exception (see below)
If I import the cert into cacerts it works. How can I access my web service without importing the cert into cacerts? Shouldn't Java trust my cert since it's signed by thawte? Or do I need to include every intermediate certificate into cacerts?
This is the code I am using to call the webservice:
QName serviceName = new QName("http://myservice.test.com/myservice", "MyService");
QName portName = new QName("http://myservice.test.com/myservice","MyServiceSOAP");
URL serviceUrl = new URL("https://myservice.test.com:443/myservice/services/MyServiceSOAP?wsdl");
Service service = Service.create(serviceUrl,serviceName);
myService = service.getPort(portName, MyService.class);
And the error trace is:
Exception in thread "main" javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException: Failed to create service.
at org.apache.cxf.jaxws.ServiceImpl.<init>(ServiceImpl.java:149)
at org.apache.cxf.jaxws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:98)
at javax.xml.ws.Service.<init>(Service.java:77)
at javax.xml.ws.Service.create(Service.java:707)
at drawbond.alex.WSClient.main(WSClient.java:28)
Caused by: org.apache.cxf.service.factory.ServiceConstructionException: Failed to create service.
at org.apache.cxf.wsdl11.WSDLServiceFactory.<init>(WSDLServiceFactory.java:100)
at org.apache.cxf.jaxws.ServiceImpl.initializePorts(ServiceImpl.java:199)
at org.apache.cxf.jaxws.ServiceImpl.<init>(ServiceImpl.java:147)
... 4 more
Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=PARSER_ERROR: Problem parsing 'https://myservice.test.com:443/myservice/services/myservicesoap'.: 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.ibm.wsdl.xml.WSDLReaderImpl.getDocument(WSDLReaderImpl.java:2198)
at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(WSDLReaderImpl.java:2390)
at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(WSDLReaderImpl.java:2422)
at org.apache.cxf.wsdl11.WSDLManagerImpl.loadDefinition(WSDLManagerImpl.java:262)
at org.apache.cxf.wsdl11.WSDLManagerImpl.getDefinition(WSDLManagerImpl.java:205)
at org.apache.cxf.wsdl11.WSDLServiceFactory.<init>(WSDLServiceFactory.java:98)
... 6 more
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 com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:647)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:189)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:812)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
at com.ibm.wsdl.xml.WSDLReaderImpl.getDocument(WSDLReaderImpl.java:2188)
... 11 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)
... 31 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:146)
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)
... 37 more
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
This exception is usually due:
Incomplete trust path for the server certificate: the server certificate is probably not trusted by the client. Usually the fix is to import the server certificate chain in into the client trust store
Bad server config, like certificate chain incomplete. In the case the fix is on server part
Thawte is by default on cacerts, so probably the problem will be incomplete chain. You can verify the server with SSLLabs check for errors in 'certificate' or 'certificate chain'.
If the chain is correct, then download, and check whether or not the site certificate is in cacerts. The simplest way to do is using the GUI tool portecle

MongoDB Java Driver doesn't adhere sslInvalidHostNameAllowed option

The following java code with MongoDB java driver 3.0.4 fails connecting to MongoDB server that is running with --sslAllowConnectionsWithoutCertificates option:
MongoClientOptions options = MongoClientOptions.builder().sslEnabled(true).sslInvalidHostNameAllowed(true).build();
ServerAddress server = new ServerAddress("127.0.0.1", 27017);
MongoClient client = new MongoClient(server, options);
client.getDatabaseNames();
The error I get is:
INFO: Exception in monitor thread while connecting to server 127.0.0.1:27017
com.mongodb.MongoSocketWriteException: Exception sending message
at com.mongodb.connection.InternalStreamConnection.translateWriteException(InternalStreamConnection.java:462)
at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:205)
at com.mongodb.connection.CommandHelper.sendMessage(CommandHelper.java:89)
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
at com.mongodb.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:83)
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:43)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127)
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:1937)
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:1478)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:212)
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:1050)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1363)
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:735)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
at com.mongodb.connection.SocketStream.write(SocketStream.java:75)
at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:201)
... 7 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:1460)
... 16 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)
... 22 more
I am trying to use SSL and avoid any certificate validation as I am unable to install any certificate on the client.
Any idea?
Consider building your MongoClientOptions with a custom SSLContext. The latter one can be build using SSLContextBuilder from Apache HttpCore:
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(TrustAllStrategy.INSTANCE)).build();
There is also an option to use TrustSelfSignedStrategy.INSTANCE or implement your own depending on your setup.

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.

Categories

Resources