Multiple truststores in play framework - jvm - java

Currently I try to make a play application be able to communicate SSL encrypted with the database.
I created self-signed certificate and CA for mysql. There is no problem with that normally, I can make the application communicate with the db server encrypted, when I add this CA to the JAVA_OPTS
-Djavax.net.ssl.trustStore=/app/path/conf/truststore
Everything goes well until my application not tries to communicate with other sites via SSL:
java.net.ConnectException: General SSLEngine problem to https://api.twitter.com/1/statuses/oembed.json?<meh>
[...]
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
[...]
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
[...]
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
[...]
The error is pretty obvious: twitter's ssl cert cannot be checked, because my truststore doesn't contains the CA which signed twitters certificate. IIRC I cannot add more than one "javax.net.ssl.trustStore" parameter for JVM, so I have to inject my CA's into the play framework. For luck, play framework supports ssl, and regarding the documentation I can add multiple truststores: https://www.playframework.com/documentation/2.4.x/WsSSL
I created a config file for ssl:
play.ws.ssl {
trustManager = {
stores = [
{ path: /path/to/truststore, type: "JKS", password = "<whatever is it" }
{ path: ${java.home}/lib/security/cacerts } # Default trust store
]
}
But when I start the server, I got the following error message:
Oops, cannot start the server.
java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
And now, I am stuck. I can inject my truststore for JVM, but when I do this, the app cannot communicate with other SSL enabled hosts - there's no cert, but when I try to add my truststore for play framework it doesn't accept it, because nobody signed my cert.
Is there a way to solve this somehow? I suspect if I take the system wide cacert file (which is used by java) and my truststore, and then I merge them with keytool, it will solve this, but this is not the best way - it would be more sane if I could pack my self signed certs next to the application.

I had the same problem for some reason my own trust store wouldn't be recognized so I ended up adding my certificate to the default keystore (${java.home}/lib/security/cacerts). You can use this command to do this (BTW cacerts default password is changeit):
keytool -v -importkeystore -srckeystore alice.p12 -srcstoretype PKCS12 -destkeystore "c:\Program Files\Java\jre1.8.0_71\lib\security\cacerts" -deststoretype JKS
Then you need to have the trustManager and the key manager defined. The trustManager points to the trust store and the keyManager to your certificate.
play.ws.ssl {
trustManager = {
stores = [
{
path: ${java.home}/lib/security/cacerts
}
]
}
keyManager = {
stores = [
{
type: "PKCS12",
path: "/Users/work/Documents/path/to/certificate/certificate.p12",
password: "pass"
}
]
}
}

That error means Play can't find the stores. Is the path correct?

I had the same error message: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty caused by empty store. According to Key store docs there could be password field in the configuration but it was ignored therefore certificates were not read from the store. I had to use PEM format or you can include certificates in config see Configure store. The password field is added/put back in commit #e867e729. I'm on Play 2.6 so I couldn't test it.

Related

web-service client - with keystore

I need to create a web service client with a keystore. But this is the error:
sun.security.provider.certpath.SunCertPathBuilderException: unable to
find valid certification path to requested target
My code:
private SSLSocketFactory getFactory() throws Exception {
File pKeyFile = new ClassPathResource("jks/dex-client-issuer-wss.jks").getFile();
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("PKIX");
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream keyInput = new FileInputStream(pKeyFile);
keyStore.load(keyInput, pass.toCharArray());
keyInput.close();
keyManagerFactory.init(keyStore, pass.toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
return context.getSocketFactory();
}
this is the http conection:
URL url = new URL("https://dexxis-demo1.gemalto.com/DEX/communication/issuer-interface");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(getFactory());
I only have a dex-client-issuer-wss.jks file which works with soap ui, how can I create a connection with this certificate file?
'unable to find valid certification path' (during SSL/TLS handshake) has nothing to do with your keystore -- it means that the server cert does not validate against your truststore, which since you passed null as the 2nd arg to context.init is the JRE's default, which is the file specified by sysprop javax.net.ssl.trustStore if set otherwise JRE/lib/security/cacerts (or .../jssecacerts if it exists).
That server is using a cert issued under the root cert Gemalto Business Root Certificate Authority which is not included in the cacerts supplied with Oracle Java packages, or any other established truststores I know, and is not known by the public transparency logs (per https://crt.sh). SoapUI, presumably because it is designed as a development, test and debug tool, ignores invalid or suspect certs, but a browser or curl or wget on that URL should fail unless the truststore(s) on your system(s) have been modified or are otherwise unusual.
OTOH openssl s_client which is also primarily a debug tool reports an error but makes the connection anyway.
If you do want to trust that CA, or one of its (two) intermediates, or the site anyway, you need to have the appropriate cert in your truststore. The usual practice is to trust the root CA cert, but Java supports using any cert in the chain, including the EE cert, as an anchor. Since you are already creating your own context, and keymanager, you might as well create your own trustmanager rather than modifying the JRE default, which is (usually) platform/environment dependent and sometimes tricky. You could fetch the desired cert and put it in a separate keystore file (see below), load that and use it to create a trustmanager. Or since you already have a keystore file for your own key+cert(s), Java supports having both a privateKey entry or entries and a trustedCert entry or entries for other party/parties in the same file, so you could just add their cert to your existing JKS and use the same KeyStore object in a TrustManagerFactory just like you have for KeyManagerFactory to create the trustmanager array for your context.
Easy ways to get the cert are:
openssl s_client -showcerts -connect host:port </dev/null (on Windows <NUL:) -- with port 443; many servers nowadays need the Server Name Indication extension (aka SNI) and for OpenSSL below 1.1.1 you must add -servername host to provide it, but this server doesn't. This outputs a PEM block for each cert from the server, with labels before each showing s: (subjectname) and i: (issuername). Note that after the first cert, which is as required the EE cert, this server sends the CA certs in top-down order not bottom-up. This is technically in violation of RFC 5246 (or earlier 4346 or 2246); RFC 8446 for TLS1.3 allows it because it was already a common extension, and Java JSSE in particular supports it.
keytool -printcert -rfc -sslserver host -- also supports host:port but the default is 443 which is okay for you. This outputs only the PEM blocks, so if you didn't already know from my previous item about the order, you would have to decode each one to find out which is which, or just experiment until you found the correct one.
In either case take the desired PEM block and put it in a file, and do
keytool -importcert -keystore jksfile -alias somealias -file thecertfile
somealias is only required to be unique within the file (which is trivial if you put it in its own file) and case-insensitive (conventionally lowercase), but should be descriptive or mnemonic, and alphanumeric only if possible. Then use the resulting file as above.

Error while consuming secure SOAP base web service in JAVA

I am new in JAVA, Consuming web service(.wsdl) in Web Service Client project. I import the client certificate in java cacerts store in jrd. My code is as follows:
System.setProperty("javax.net.ssl.trustStore","[PATH]/cacerts.jks");
System.setProperty("javax.net.ssl.trustStorePassword","changeit");
ServicesProxy service = new ServicesProxy();
ServiceRequest request = new ServiceRequest(1498);
ServiceResponse response = service.getDetails(request);
I'm failed to handshake, I am getting 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
I have no clue why there is an exception. Any help will be appreciated.
You probably have to add the key chain in the certificate (PEM format).
CA Root -> Intermediate Cert -> Cert.
Or the certificate cannot be found in the keystore, do you use the correct alias etc.
And I do not recognize the SOAP JAX-WS implementation you use.
Not a solution to your problem, but maybe it helps to find it:
You can start your client with the VM parameter -Djavax.net.debug=all which will give you a lot of information about the SSL connection.
Check here for details about the output:
https://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/ReadDebug.html
Use -Djavax.net.ssl.trustStore property directly instead.
One more thing the server you use in that also u need to place the jks for handshake.
For example server is JBoss then bin
I guess your cacert is not correct or the path is unaccessible. I followed the instructions given here
Use SSL Poke to verify connectivity
Download SSLPoke.class
Execute the class as follows, changing the URL and port:
$JAVA_HOME/bin/java SSLPoke yoururl 443
A successful connection would look like this:
$JAVA_HOME/bin/java SSLPoke yoururl 443
Successfully connected
Try to use a different truststore to connect
$JAVA_HOME/bin/java -Djavax.net.ssl.trustStore=[PATH]/cacerts.jks SSLPoke yoururl 443
If it fails the truststore does not contain the proper certificates.
How to solve it
The solution is extracted from here
Fetch the certificate again from the server:
openssl s_client -connect yoururl:443
You need openssl. Save the output to a file called public.crt. This is how your file should look like:
-----BEGIN CERTIFICATE-----
< Bunch of lines of your certificate >
-----END CERTIFICATE-----
Import the certificate:
$JAVA_HOME/bin/keytool -import -alias -keystore $JAVA_HOME/jre/lib/security/cacerts -file public.crt
Enter the password if prompted (the default is changeit)
Recommendation
In the same post it is not recommended to use a configured trustStore different than the JVM cacert because then java could not access other root certificates.
This is a quite common error while dealing with soap services over SSL, I've had it a few times.
Your certificate may not be correctly installed in your truststore.
You can use openssl to check and install the correct certificate in the truststore, as explained here
Hi Looks like certificates are not imported correctly or path used in code not pointing to correct keystore.
I hope following steps in below article will help you.
http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html

WildFly 11 - Use certificate to make https requests

I'm a bit lost of how I can use certificate in WidlFly 11. I re the doccumentation and found a lot of terms like JSSE, OpenSSL, Elytron, ApplicationRealm.
The problem occurs when I execute the code
final URL url = new URL("https://someUrl");
HttpsURLConnection httpURLConnection = (HttpsURLConnection)url.openConnection();
This exception is thrown sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
So, what exactly need to configure? I tried the section "Enable One-way SSL/TLS for Applications" in Elytron Doccumentation but didn't works.
ps: I'm using java 9.01
ps2: I'm using standalone-full.xml
let me know if you need more informations
This is unrelated to WildFly - you need to configure certificates trusted by java URL connections - you need to create and configure truststore:
create keystore containing certificate of server (if it is self-signed certificate), or better, certificate of its CA:
keytool -import -file myCA.cert -alias myCA -storepass mypassword -noprompt -keystore my.truststore
start using created keystore file as truststore in WildFly by setting javax.net.ssl.trustStore and javax.net.ssl.trustStorePassword system properties:
bin/jboss-cli.sh -c
/system-property=javax.net.ssl.trustStore:add(value="/path/to/my.truststore")
/system-property=javax.net.ssl.trustStorePassword:add(value="mypassword")
Elytron documentation you mention is related only to server side - but this is client side configuration, which is not currently handled by it.
The certificate is not trusted, iirc there is a self-signed certificate in WildFly 11 so yo need to trust it or install a real certificate.
Accept server's self-signed ssl certificate in Java client

Invoking HTPS WebService from java

I am trying to access a web service which has SSL enabled from stand alone java program . I was able to generate client from WSDL however when i am trying to invoke web service i get SSL handshake issue . Below is java code
TestWebService sh = (TestWebService) shs.getTestWebServiceExportTestWebServiceHttpPort();
BindingProvider port = (BindingProvider)sh;
port.getRequestContext().put(BindingProvider.
ENDPOINT_ADDRESS_PROPERTY, args[0]);
System.out.println( ((BindingProvider)sh).toString() );
The url that is lets say https://service.test.com/sca/TestWebService?wsdl
Below is the error message
Failed to access the WSDL at:
https://service.testwebservice.com/TestWebServiceExport?wsdl. It failed with:
Got com.ibm.jsse2.util.j: PKIX path building failed: java.security.cert.CertPathBuilderException: PKIXCertPathBuilderImpl could not build a valid CertPath.; internal cause is:
java.security.cert.CertPathValidatorException: The certificate issued by CN=Corp Production Root CA V1, O=Cord Inc. is not trusted; internal cause is:
java.security.cert.CertPathValidatorException: Certificate chaining error while opening stream from https://service.testwebservice.com/TestWebServiceExport?wsdl.
I have installed the ceritificate in IE browser from website but still no luck .
You are on the right track by installing the cert into IE browser - that would allow IE to access the web service without error. However, as your client is Java (and not IE), you need to install the cert into Java.
The Java command for doing this is as follows:
$JAVAHOME/bin/keytool -import -alias service.test.com -keystore $JAVA_HOME/jre/lib/security/cacerts -file ~/certfile.pem
Note: this will install the cert into the default keystore for that Java install. This will affect all Java processes using that JVM. The default password for the keystore is 'changeit'

issues in connecting to AD server over SSL?

I had to enable SSL over Active Directory server, to do that I followed each and every steps mentioned here: http://www.linuxmail.info/enable-ldap-ssl-active-directory/
Now I am not sure if SSL is really enabled properly?
On server itself if I run ldp, I think I can connect on 636 port. However on my system I don't see SSL option on ldp client?
I've two other LDAP clients (Softerra LDAP Browser and Apache Directory Studio) but I am not able to connect using ldaps (on 636 port). I guess I'll need to import certificate used in AD server so these tools can trust that self sign certificate which I used on AD server.
Using Java code, I've added certificate into cacerts (got certificate using steps mentioned here: http://www.linuxmail.info/export-ssl-certificate-windows-2003/), however I still can't connect to AD using SSL.
I tried SSL as well as TSL:
TLS:
// got LdapContext using ldap (not with ldaps)
StartTlsResponse tls = (StartTlsResponse)ctx.extendedOperation(new StartTlsRequest());
It gives 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
SSL:
String ldapURL = "ldaps://<domain-name>:636";
String keystore = "C:/Oracle/Middleware/jdk160_24/jre/lib/security/cacerts";
System.setProperty("javax.net.ssl.trustStore",keystore);
env.put(Context.SECURITY_PROTOCOL,"ssl");
// other properties are set in env
LdapContext ctx = new InitialLdapContext(env, null);
It gives following exception:
javax.naming.CommunicationException: <domain-name>:636 [Root exception is java.net.ConnectException: Connection timed out: connect]
Can anyone please suggest where I am wrong?
Thanks.
This one was fixed.
I was using wrong (rather incomplete) command to import certificate.
I was using:
keytool -import -alias mycert -keystore cacerts -file d:\mycert.cer
When I used follwing:
keytool -import -noprompt -trustcacerts -alias mycert -file c:/mycert.cer -keystore C:/Oracle/Middleware/jdk160_24/jre/lib/security/cacerts -storepass changeit
And it started working.
If you can't get TLS to work, it is unlikely that SSL will work. Are you sure that you got the right certificate and configured the keystore correctly? Based on the SSLHandshakeException when trying to use TLS, it would seem that may not be set up correctly.
Check out this SO answer for some tips on how to verify that your keystore is correctly set up: https://stackoverflow.com/a/9619478/1792088

Categories