We have the requirement to use SSL client certificate for a JMS connection to an IBM MQ server. I already asked a question specifically for Websphere MQ but then I learned that this is mainly the job of JSSE and can be configured via Java System Properties (e.g. -Djavax.net.ssl.keyStore=<location of keyStore>).
But since there are already active keystores for other parts of the application within our WildFly 9 AS, I'm looking for a way to enable a specific keystore just for the JMS part - can this be done?
Yes it is possible for an MQ classes for JMS application to use a specific keystore and truststore when creating secure connections to a queue manager.
By default, the MQ classes for JMS will use the standard javax.net.ssl System Properties to determine which certificate store to use as the key and trust stores. However, you can customise this by building your own javax.net.ssl.SSLSocketFactory object that gets set on the JMS Connection Factory used by your application.
See the Knowledge Center for further details:
https://www.ibm.com/support/knowledgecenter/SSFKSJ_9.0.0/com.ibm.mq.dev.doc/q032450_.htm
This typically means you have to programmatically build or update a JMS Connection Factory within application code, rather than via administration only and updating a JNDI definition - which is somewhat unfortunate.
I know you have stated you are using WildFly as your application server of choice, but just for your awareness, WebSphere Application Server (WSAS) allows you to configure a JMS Connection Factory within JNDI and have a separate SSL/TLS configuration (containing certificate store information, Cipher Suites etc) that can be associated with the JMS resources. WSAS will then take care of creating the SSLSocketFactory and setting it appropriately on the JMS Connection Factory when an application uses it to create a JMS Connection or Context.
As such, you continue to define your resources (JMS and SSL) administratively via the WSAS Administration Console or wsadmin scripting without having to insert specific logic within the application to do this, which is obviously preferred.
WildFly (and other JEE app servers) might offer similar functionality, but I do not know.
This maybe a little too late, but may help others. I was able to get it to work using JmsFactoryFactory,MQConnectionFactory, JKS trustStore and keyStore generated from a Certificate with the following code:
try {
JmsFactoryFactory factoryFactory = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
jmsConnectionFactory = (MQConnectionFactory) factoryFactory.createConnectionFactory();
SSLContext sslContext = createSSlContext();
setSSLSystemProperties();
jmsConnectionFactory.setSSLSocketFactory(sslContext.getSocketFactory());
// Set the properties
jmsConnectionFactory.setStringProperty(WMQConstants.WMQ_HOST_NAME, hostName);
jmsConnectionFactory.setIntProperty(WMQConstants.WMQ_PORT, port);
jmsConnectionFactory.setStringProperty(WMQConstants.WMQ_CHANNEL, channel);
jmsConnectionFactory.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
jmsConnectionFactory.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, APPLICATION_NAME);
jmsConnectionFactory.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, false);
jmsConnectionFactory.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SUITE, cipherSuite);
return jmsConnectionFactory;
} catch (JMSException ex) {}
SSL Context
private SSLContext createSSlContext() throws NoSuchAlgorithmException {
SSLContext sslContext = SSLContext.getInstance("TLS");
try {
// Load KeyStore
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(toInputStream(keyStorePath), keyStorePassword.toCharArray());
// Load TrustStore
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(toInputStream(trustStorePath), trustStorePassword.toCharArray());
// Set KeyManger from keyStore
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keyStore, keyStorePassword.toCharArray());
// Set TrustManager from trustStore
TrustManagerFactory trustFact = TrustManagerFactory.getInstance("SunX509");
trustFact.init(trustStore);
// Set Context to TLS and initialize it
sslContext.init(kmf.getKeyManagers(), trustFact.getTrustManagers(), null);
return sslContext;
} catch (Exception ex) {
LOG.error("Unable to load the SSL Config", ex);
}
return sslContext;
}
I've never worked with IBM MQ but i solved the similar task for various application containers and databases. As i can see from documentation it's possible to specify custom ssl connection factory for MQ using this method MQConnectionFactory.setSSLSocketFactory().
So yes, it's definitely possible to address your requirements and basically your task is to build a dedicated ssl socket factory for MQ connections.
Here is code snippets for this:
Utility class for generating in-memory keystores and truststores.
Java keyloader supports only pkcs8 private keys out of the box. To load pem keys some external library like BouncyCastle should be used.
It's possible to generate pkcs8 keys from pem keys using openssl.
public class KeystoreGenerator {
private KeystoreGenerator() {
}
public static KeyStore generateTrustStore(CertificateEntry certificateEntry) throws Exception {
return generateTrustStore(Collections.singletonList(certificateEntry));
}
public static KeyStore generateTrustStore(Collection<CertificateEntry> certificateEntries) throws Exception {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
for (CertificateEntry certificateEntry : certificateEntries) {
Certificate certificate = certFactory.generateCertificate(certificateEntry.getCertificate());
keyStore.setCertificateEntry(certificateEntry.getAlias(), certificate);
}
return keyStore;
}
public static KeyStore generateKeystore(PrivateKeyCertificateEntry privateKeyCertificateEntry) throws Exception {
return generateKeystore(Collections.singletonList(privateKeyCertificateEntry));
}
public static KeyStore generateKeystore(Collection<PrivateKeyCertificateEntry> privateKeyCertificateEntries) throws Exception {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
for (PrivateKeyCertificateEntry privateKeyCertificateEntry : privateKeyCertificateEntries) {
Certificate certificate = certFactory.generateCertificate(privateKeyCertificateEntry.getCertificate());
keyStore.setCertificateEntry(privateKeyCertificateEntry.getAlias(), certificate);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(IOUtils.toByteArray(privateKeyCertificateEntry.getKey()));
PrivateKey privateKey = keyFactory.generatePrivate(spec);
keyStore.setKeyEntry(privateKeyCertificateEntry.getAlias(), privateKey,
privateKeyCertificateEntry.getPassword(), new Certificate[]{certificate});
}
return keyStore;
}
public static class CertificateEntry {
private final InputStream certificate;
private final String alias;
// constructor, getters and setters
}
public static class PrivateKeyCertificateEntry {
private final InputStream key;
private final InputStream certificate;
private final String alias;
private final char[] password;
// constructor, getters and setters
}
}
The next code creates ssl socket factory for MQ using dedicated keystore and truststore. This code loads keys and certificates from disk as class path resources. It's also possible to store them only in memory using OS environment variables and some extra effort during client application deployment.
public SSLSocketFactory generateMqSSLSocketFactory() throws Exception {
KeyStore keyStore = KeystoreGenerator.generateKeystore(new KeystoreGenerator.PrivateKeyCertificateEntry(
getClass().getResourceAsStream("/keys/mq-client-key.pkcs8"),
getClass().getResourceAsStream("/keys/mq-client-certificate.pem"),
"mq_client", "changeit".toCharArray()
));
// Generate keystore to authorize client on server
KeyStore trustStore = KeystoreGenerator.generateTrustStore(new KeystoreGenerator.CertificateEntry(
getClass().getResourceAsStream("/keys/mq-server-certificate.pem"), "mq_server"));
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, "changeit".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return sslContext.getSocketFactory();
}
And then set this ssl socket factory to mq connection factory using MQConnectionFactory.setSSLSocketFactory() method. Seems that IBM MQ is a proprietary library so unfortunately i can't test it, but i guess such configuration should work.
Related
I have a Kubernetes Deployment of my Spring Boot application where I used to update global Java cacerts using keytool at the bootstrap:
keytool -noprompt -import -trustcacerts -cacerts -alias $ALIAS -storepass $PASSWORD
However, I need to make the container immutable using the readOnlyRootFilesystem: true in the securityContext of the image in my Deployment. Therefore, I cannot update the cacert like that with additional certificates to be trusted.
Additional certificates that should be trusted are provided as environment variable CERTS.
I assume that the only proper way would be to do this programmatically, for example during #PostConstruct in the Spring Boot component.
I was looking into some examples how to set the global truststore in code, but all of them refer to update the cacerts and then save it to filesystem, which does not work for me.
Some examples use System.setProperty("javax.net.ssl.trustStore", fileName);, but this does not work either on the read-only filesystem, where I cannot update file.
Another examples suggest to use X509TrustManager, but if I understood correctly, this does not work globally.
Is there any way in Java or Spring Boot to update global truststore in general programmatically so every operation in the code will use and I do not have to implement something like TrustManager to every connection? My goal is to have it imported at the begging (similar like it is done using shell and keytool). Without touching the filesystem, as it is read-only.
You can use the following approach to update the Java truststore programmatically without modifying the read-only filesystem:
Create a KeyStore object in your code.
Load the existing truststore into the KeyStore object using the
truststore password.
Parse the environment variable CERTS and add the certificates to the
KeyStore object.
Use the javax.net.ssl.TrustManagerFactory to create a
TrustManagerFactory with the KeyStore.
Use the TrustManagerFactory to initialize a SSLContext with the
trustmanager.
Use the SSLContext.init() method to set the SSL context as the
default for all SSL connections.
You can achieve this in a Spring Boot component:
#PostConstruct
public void configureGlobalTrustStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream inputStream = getClass().getResourceAsStream("/cacerts");
trustStore.load(inputStream, "changeit".toCharArray());
inputStream.close();
String certString = System.getenv("CERTS");
if (certString != null) {
String[] certArray = certString.split(" ");
for (int i = 0; i < certArray.length; i++) {
InputStream certInput = new ByteArrayInputStream(Base64.getDecoder().decode(certArray[i]));
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(certInput);
certInput.close();
trustStore.setCertificateEntry("cert-" + i, cert);
}
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
SSLContext.setDefault(sslContext);
}
This way, every SSL connection in your code will use the updated truststore, without having to configure it for each individual connection.
I am attempting to convert an existing application that uses the org.java-websocket library to allow the webserver to communicate using https instead of the previous http. After researching, the only example I was able to find is here:
https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/example/SSLServerExample.java
public static void main(String[] args) throws Exception {
ChatServer chatserver = new ChatServer(
8887); // Firefox does allow multible ssl connection only via port 443 //tested on FF16
// load up the key store
String STORETYPE = "JKS";
String KEYSTORE = Paths.get("src", "test", "java", "org", "java_websocket", "keystore.jks")
.toString();
String STOREPASSWORD = "storepassword";
String KEYPASSWORD = "keypassword";
KeyStore ks = KeyStore.getInstance(STORETYPE);
File kf = new File(KEYSTORE);
ks.load(new FileInputStream(kf), STOREPASSWORD.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, KEYPASSWORD.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
SSLContext sslContext = null;
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
chatserver.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext));
chatserver.start();
}
The only problem with this is that I'm hesitant because it seems to be wanting you to access the keystore.jks and provide to the store password + keypassword and also seems to expect the KeyStore file to be on the running computer (or somewhere released with the software). Isn't this a security risk?
I already have the jar signed with the keystore, perhaps there is nothing more that I need to do? Can someone point me to a different example if this is not the way to do this?
This keystore I'm using is the one provided to us by an external company to our company to sign our java applications. Perhaps this is not the keystore I should be using and need to make one for this single app independently of that one?
I am trying to initialise a SSLContext with a custom truststore and keeping keystore and secureRandom as default. For the custom truststore I have a JKS file which I will use to initialise TrustManagers.
This is a server application which will get multiple concurrent requests. I am not able to understand if we should use a singleton SSLContext/SSLSocketFactory or not. Based on Are SSLContext and SSLSocketFactory createSocket thread safe?, it looks like we should create new objects for every request. But then, the below implementation will cause high latency for loading truststore and creating SSL object for every request. Is this understanding correct?
Also, it will be very helpful if I could understand how to check if a particular object can be singleton in such cases? In the documentation I generally look for mention about being thread safe, but I could not find any such information in oracle documentation for SSLContext/SSLSocketFactory.
URL url = new URL(endpoint);
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(getDefaultSSLSocketFactory());
public SSLSocketFactory getDefaultSSLSocketFactory() {
String path = "path to truststore";
try (FileInputStream fis = new FileInputStream(path)) {
SSLContext sslcontext = SSLContext.getInstance("TLSv1.2");
KeyStore clientKeyStore = KeyStore.getInstance("JKS");
clientKeyStore.load(fis, "password".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(clientKeyStore);
sslcontext.init(null, trustManagerFactory.getTrustManagers(), null);
return sslcontext.getSocketFactory();
}
Small question regarding Netty, Spring Webflux, and how to send http requests to multiples downstream systems, when each of the downstream require mTLS and a different client certificate is required to send requests to each please?
What I have so far in my Java 11 Spring Webflux 2.4.2 app for sending request is:
#Bean
#Primary
public WebClient getWebClient() {
return WebClient.create().mutate().defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).clientConnector(new ReactorClientHttpConnector(HttpClient.create().wiretap(true).secure(sslContextSpec -> sslContextSpec.sslContext(getSslContext())))).build();
}
And for the Netty SslContext (it is not an apache SSLContext btw)
public SslContext getSslContext() {
try {
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
try (InputStream file = new FileInputStream(keyStorePath)) {
final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(file, keyStorePassPhrase.toCharArray());
keyManagerFactory.init(keyStore, keyPassPhrase.toCharArray());
}
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
try (InputStream trustStoreFile = new FileInputStream(trustStorePath)) {
final KeyStore trustStore = KeyStore.getInstance(trustStoreType);
trustStore.load(trustStoreFile, trustStorePassPhrase.toCharArray());
trustManagerFactory.init(trustStore);
}
return SslContextBuilder.forClient().keyManager(keyManagerFactory).trustManager(trustManagerFactory).build();
} catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException | UnrecoverableKeyException e) {
return null;
}
}
This is even working perfectly fine when we only need to send request to only one downstream.
This is even working if there are multiple downstream, and they accept the same client certificate!
But problem arise when each downstream requires me to use their respective client certificate.
May I ask how to achieve this please?
Thank you
Option 1
The most straightforward solution would be using a specific client for each downstream api. And having each client configured with their specific client key and trust material.
Option 2
But your question is: how to use SslContext with multiple client certificates please?
So I want to give you some code examples to have a working setup. But the short answer is: yes it is possible!
The long answer is that you need some additional configuration to make it working. Basically what you need to do is create a keymanagerfactory from your keystore-1 and get the keymanager from the keymanagerfactory and repeat that for the other two keystores. Afterwords you will have 3 keymanagers. The next step is to have a special kind of keymanager which can be supplied to the Netty SslContext. This special kind of keymanager has the ability to iterate through the 3 keymanagers which you have created earlier and it will select the correct key material to communicate with the server. What you need is a CompositeKeyManager and CompositeTrustManager which is mentioned at the following stackoverflow answer here: Registering multiple keystores in JVM
The actual code snippet will be the below. I disregarded the loading file with inputstream and creating the keystore file and creating the keymanagerfactory as you already know how to do that.
KeyManager keyManagerOne = keyManagerFactoryOne.getKeyManagers()[0]
KeyManager keyManagerTwo = keyManagerFactoryTwo.getKeyManagers()[0]
KeyManager keyManagerThree = keyManagerFactoryThree.getKeyManagers()[0]
List<KeyManager> keyManagers = new ArrayList<>();
keyManagers.add(keyManagerOne);
keyManagers.add(keyManagerTwo);
keyManagers.add(keyManagerThree);
CompositeX509KeyManager baseKeyManager = new CompositeX509KeyManager(keyManagers);
//repeat the same for the trust material
TrustManager trustManagerOne = trustManagerFactoryOne.getTrustManagers()[0]
TrustManager trustManagerTwo = trustManagerFactoryTwo.getTrustManagers()[0]
TrustManager trustManagerThree = trustManagerFactoryThree.getTrustManagers()[0]
List<TrustManager> trustManagers = new ArrayList<>();
trustManagers.add(trustManagerOne);
trustManagers.add(trustManagerTwo);
trustManagers.add(trustManagerThree);
CompositeX509TrustManager baseTrustManager = new CompositeX509TrustManager(trustManagers);
SslContext sslContext = SslContextBuilder.forClient()
.keyManager(baseKeyManager)
.trustManager(baseTrustManager)
.build();
And the above code should give you the capability of using multiple key and trust for a single client. This client will be able to communicate with the different downstream api's with the different key and trust material.
The downside of this setup is that you require to copy and paste the CompositeKeyManager and CompositeTrustManager into your code base and that the setup is a bit verbose. Java does not provide something out of the box for this use-case.
Option 3
If you want a a bit simpeler setup I would suggest you the code snippet below:
import io.netty.handler.ssl.SslContext;
import nl.altindag.ssl.SSLFactory;
import nl.altindag.ssl.util.NettySslUtils;
public class App {
public static void main(String[] args) {
SSLFactory sslFactory = SSLFactory.builder()
.withIdentityMaterial(keyStorePathOne, password)
.withIdentityMaterial(keyStorePathTwo, password)
.withIdentityMaterial(keyStorePathThree, password)
.withTrustMaterial(trustStorePathOne, password)
.withTrustMaterial(trustStorePathTwo, password)
.withTrustMaterial(trustStorePathThree, password)
.build();
SslContext sslContext = NettySslUtils.forClient(sslFactory).build();
}
}
I need to provide some disclaimer, I am the maintainer of the library of the code snippet above. The library is available here: GitHub - SSLContext Kickstart and it uses the same CompositeKeyManager and CompositeTrustManager under the covers which I mentioned earlier for option 2.
And you can add it to your pom with the following snippet:
<dependency>
<groupId>io.github.hakky54</groupId>
<artifactId>sslcontext-kickstart-for-netty</artifactId>
<version>7.4.9</version>
</dependency>
I need to create a javax.net.ssl.SSLSocketFactory that establish a TLS connection but ignores the validation of the server certificate. Not for HTTP protocol. I know this is not the right thing to do, but I NEED it. I don't want or like it.
I made an implementation that works but validate the server cert (as it supposes to be) implementation looks as following:
/**
* Provide a quick method to construct a SSLSocketFactory which is a TCP socket using TLS/SSL
* #param trustStore location of the trust store
* #param keyStore location of the key store
* #param trustStorePassword password to access the trust store
* #param keyStorePassword password to access the key store
* #return the SSLSocketFactory to create secure sockets with the provided certificates infrastructure
* #exception java.lang.Exception in case of something wrong happens
* */
static public SSLSocketFactory getSocketFactory ( final String trustStore, final String keyStore, final String trustStorePassword, final String keyStorePassword) throws Exception
{
// todo check if the CA needs or can use the password
final FileInputStream trustStoreStream = new FileInputStream(trustStore);
final FileInputStream keyStoreStream = new FileInputStream(keyStore);
// CA certificate is used to authenticate server
final KeyStore caKs = KeyStore.getInstance("JKS");
caKs.load(trustStoreStream, trustStorePassword.toCharArray());
final TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(caKs);
trustStoreStream.close();
// client key and certificates are sent to server so it can authenticate us
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(keyStoreStream, keyStorePassword.toCharArray());
final KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
kmf.init(ks, keyStorePassword.toCharArray());
keyStoreStream.close();
// finally, create SSL socket factory
final SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return context.getSocketFactory();
}
The solution would be to create a dummy X509TrustManager class that basically accepts all server certs without checking.
Then create an instance and pass it as the 2nd argument in your SSLContext::init call.
But seriously, this is a bad idea. If you are not going to check the CERT, then using SSL is pointless or worse1.
1 - Here's my theory. You have been told by your security folks that using MTTQ over an insecure channel is dangerous. Or they have blocked port 1883. But you have a MTTQ / SSL server that you can't be bothered to get a proper CERT for. So you are just trying to throw something together that "works". Guess what. If the people who told you to use SSL find out, they will have your guts for garters! And if you are not doing this for this reason, then ... well ... what you are doing makes no sense. Even a self-signed server CERT is better than this. You just need to add it as a trusted cert in the client-side keystore.