100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Full X.509 mTLS support for MQTT clients and MQTT Agent (#1351)
Panos Kalogeropoulos0cd7b7df103a
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/AbstractMQTT_IOClient.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/AbstractMQTT_IOClient.javaindex 8434619fd..f44433852 100644--- a/agent/src/main/java/org/openremote/agent/protocol/mqtt/AbstractMQTT_IOClient.java+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/AbstractMQTT_IOClient.java@@ -20,6 +20,8 @@package org.openremote.agent.protocol.mqtt;import com.hivemq.client.mqtt.MqttClient;+import com.hivemq.client.mqtt.MqttClientSslConfig;+import com.hivemq.client.mqtt.MqttClientSslConfigBuilder;import com.hivemq.client.mqtt.MqttClientState;import com.hivemq.client.mqtt.exceptions.ConnectionClosedException;import com.hivemq.client.mqtt.exceptions.ConnectionFailedException;@@ -41,6 +43,8 @@ import org.openremote.model.auth.UsernamePassword;import org.openremote.model.syslog.SyslogCategory;import org.openremote.model.util.ValueUtil;+import javax.net.ssl.KeyManagerFactory;+import javax.net.ssl.TrustManagerFactory;import java.net.URI;import java.util.HashMap;import java.util.HashSet;@@ -74,11 +78,11 @@ public abstract class AbstractMQTT_IOClient<S> implements IOClient<MQTTMessage<Sprotected final AtomicBoolean connected = new AtomicBoolean(false); // Used for subscriptionsprotected Consumer<String> topicSubscribeFailureConsumer;- protected AbstractMQTT_IOClient(String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI, MQTTLastWill lastWill) {- this(UniqueIdentifierGenerator.generateId(), host, port, secure, cleanSession, usernamePassword, websocketURI, lastWill);+ protected AbstractMQTT_IOClient(String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI, MQTTLastWill lastWill, KeyManagerFactory keyManagerFactory, TrustManagerFactory trustManagerFactory) {+ this(UniqueIdentifierGenerator.generateId(), host, port, secure, cleanSession, usernamePassword, websocketURI, lastWill, keyManagerFactory, trustManagerFactory);}- protected AbstractMQTT_IOClient(String clientId, String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI, MQTTLastWill lastWill) {+ protected AbstractMQTT_IOClient(String clientId, String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI, MQTTLastWill lastWill, KeyManagerFactory keyManagerFactory, TrustManagerFactory trustManagerFactory) {this.clientId = clientId;this.host = host;this.port = port;@@ -123,7 +127,13 @@ public abstract class AbstractMQTT_IOClient<S> implements IOClient<MQTTMessage<S.applyAutomaticReconnect();if (secure) {- builder = builder.sslWithDefaultConfig();+ MqttClientSslConfigBuilder sslBuilder = MqttClientSslConfig.builder();+ if (keyManagerFactory != null) {+ sslBuilder = sslBuilder.keyManagerFactory(keyManagerFactory);+ } if (trustManagerFactory != null) {+ sslBuilder = sslBuilder.trustManagerFactory(trustManagerFactory);+ }+ builder = builder.sslConfig(sslBuilder.build());}if (websocketURI != null) {diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomKeyManagerFactory.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomKeyManagerFactory.javanew file mode 100644index 000000000..0b374dd4a--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomKeyManagerFactory.java@@ -0,0 +1,35 @@+/*+ * Copyright 2024, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */++package org.openremote.agent.protocol.mqtt;++import javax.net.ssl.KeyManagerFactory;+import java.security.Provider;++public class CustomKeyManagerFactory extends KeyManagerFactory {++ public CustomKeyManagerFactory(String userRequestedAlias) {+ super(+ new CustomKeyManagerFactorySpi(userRequestedAlias),+ new Provider("CustomKeyManagerFactory", "1.0", "Custom Key Manager Factory") {},+ KeyManagerFactory.getDefaultAlgorithm()+ );+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomKeyManagerFactorySpi.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomKeyManagerFactorySpi.javanew file mode 100644index 000000000..0b566c4f8--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomKeyManagerFactorySpi.java@@ -0,0 +1,137 @@+/*+ * Copyright 2024, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */++package org.openremote.agent.protocol.mqtt;++import javax.net.ssl.*;+import java.net.Socket;+import java.security.*;+import java.security.cert.X509Certificate;+import java.util.Arrays;+import java.util.Optional;+import java.util.logging.Logger;++public class CustomKeyManagerFactorySpi extends KeyManagerFactorySpi {++ private X509ExtendedKeyManager keyManager;+ private final String realmPrefixedAlias;++ public CustomKeyManagerFactorySpi(String realmPrefixedAlias) {+ this.realmPrefixedAlias = realmPrefixedAlias;+ }++ @Override+ protected void engineInit(KeyStore keyStore, char[] password) {+ KeyManagerFactory factory = null;+ try {+ factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());+ factory.init(keyStore, password);+ } catch (Exception e) {+ throw new RuntimeException(e);+ }++ for (KeyManager keyManager : factory.getKeyManagers()) {+ if (keyManager instanceof X509ExtendedKeyManager) {+ this.keyManager = new CustomX509KeyManager((X509ExtendedKeyManager) keyManager, realmPrefixedAlias);+ return;+ }+ }+ throw new IllegalStateException("No X509KeyManager found");+ }+++ @Override+ protected void engineInit(ManagerFactoryParameters parameters) {+ throw new UnsupportedOperationException("engineInit(KeyManagerFactorySpi.Parameters) not supported");+ }++ @Override+ protected KeyManager[] engineGetKeyManagers() {+ return new KeyManager[]{keyManager};+ }++ private static class CustomX509KeyManager extends X509ExtendedKeyManager {++ private final X509ExtendedKeyManager keyManager;+ private final String realmPrefixedAlias;+ private static final Logger LOG = Logger.getLogger(CustomX509KeyManager.class.getName());++ public CustomX509KeyManager(X509ExtendedKeyManager keyManager, String realmPrefixedAlias) {+ this.keyManager = keyManager;+ this.realmPrefixedAlias = realmPrefixedAlias;+ }++ @Override+ public String[] getClientAliases(String keyType, Principal[] issuers) {+ return keyManager.getClientAliases(keyType, issuers);+ }++ @Override+ public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {+ return keyManager.chooseClientAlias(keyType,issuers,socket);+ }++ @Override+ public String[] getServerAliases(String keyType, Principal[] issuers) {+ return keyManager.getServerAliases(keyType, issuers);+ }++ @Override+ public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) {+ for (String key : keyType) {+ String[] aliasArray = keyManager.getClientAliases(key, issuers);+ if (aliasArray == null) continue;+ Optional<String> found = Arrays.stream(aliasArray).filter(this::isCorrectAlias).findFirst();+ if(found.isPresent()){+ return found.get();+ }+ }+ //TODO: Not sure how this should be handled. This would mean that the keypair with realmPrefixedAlias+ // either wasn't found, or didn't match up with the KeyType, or does not have the correct issuer.+ // for now, log the issue that the certificate wasn't found, and then return null.++ LOG.severe("Could not find a certificate with Alias "+ this.realmPrefixedAlias);+ return null;+ }++ private boolean isCorrectAlias(String s) {+ return s.equals(this.realmPrefixedAlias);+ }++ @Override+ public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {+ return keyManager.chooseEngineServerAlias(keyType, issuers, engine);+ }++ public String chooseServerAlias(String keyType, Principal[] issuers, java.net.Socket socket) {+ return keyManager.chooseServerAlias(keyType,issuers,socket);+ }++ @Override+ public X509Certificate[] getCertificateChain(String alias) {+ return keyManager.getCertificateChain(alias);+ }++ @Override+ public PrivateKey getPrivateKey(String alias) {+ return keyManager.getPrivateKey(alias);+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomX509TrustManager.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomX509TrustManager.javanew file mode 100644index 000000000..7987866fd--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomX509TrustManager.java@@ -0,0 +1,90 @@+/*+ * Copyright 2024, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */++package org.openremote.agent.protocol.mqtt;++import javax.net.ssl.TrustManagerFactory;+import javax.net.ssl.X509TrustManager;+import java.security.KeyStore;+import java.security.cert.CertificateException;+import java.security.cert.X509Certificate;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.List;++public class CustomX509TrustManager implements X509TrustManager {++ private final X509TrustManager[] trustManagers;++ public CustomX509TrustManager(KeyStore... keyStores) throws Exception {+ List<X509TrustManager> trustManagerList = new ArrayList<>();+ for (KeyStore keyStore : keyStores) {+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());+ tmf.init(keyStore);+ for (javax.net.ssl.TrustManager tm : tmf.getTrustManagers()) {+ if (tm instanceof X509TrustManager) {+ trustManagerList.add((X509TrustManager) tm);+ }+ }+ }+ trustManagers = trustManagerList.toArray(new X509TrustManager[0]);+ }++ private X509Certificate[] mergeCertificates() {+ ArrayList<X509Certificate> resultingCerts = new ArrayList<>();+ for (X509TrustManager tm : trustManagers) {+ resultingCerts.addAll(Arrays.asList(tm.getAcceptedIssuers()));+ }+ return resultingCerts.toArray(new X509Certificate[0]);+ }++ @Override+ public X509Certificate[] getAcceptedIssuers() {+ return mergeCertificates();+ }++ @Override+ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {+ for (X509TrustManager tm : trustManagers) {+ try {+ tm.checkServerTrusted(chain, authType);+ return;+ } catch (CertificateException e) {+ // continue to the next trust manager+ }+ }+ // If none of the trust managers trust the certificate chain, throw an exception+ throw new CertificateException("None of the trust managers trust this certificate chain");+ }++ @Override+ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {+ for (X509TrustManager tm : trustManagers) {+ try {+ tm.checkClientTrusted(chain, authType);+ return;+ } catch (CertificateException e) {+ // continue to the next trust manager+ }+ }+ // If none of the trust managers trust the certificate chain, throw an exception+ throw new CertificateException("None of the trust managers trust this certificate chain");+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomX509TrustManagerFactory.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomX509TrustManagerFactory.javanew file mode 100644index 000000000..45bdecdb2--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomX509TrustManagerFactory.java@@ -0,0 +1,32 @@+/*+ * Copyright 2024, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */++package org.openremote.agent.protocol.mqtt;++import javax.net.ssl.TrustManagerFactory;+import java.security.KeyStore;+import java.security.KeyStoreException;+import java.security.Provider;++public class CustomX509TrustManagerFactory extends TrustManagerFactory {+ public CustomX509TrustManagerFactory(KeyStore... keystores) throws KeyStoreException {+ super(new CustomX509TrustManagerFactorySpi(keystores), new Provider("CustomX509TrustManagerFactory", "1.0", "Custom X509 Trust Manager Factory") {}, TrustManagerFactory.getDefaultAlgorithm());+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomX509TrustManagerFactorySpi.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomX509TrustManagerFactorySpi.javanew file mode 100644index 000000000..bebb28a7a--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/CustomX509TrustManagerFactorySpi.java@@ -0,0 +1,140 @@+/*+ * Copyright 2024, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */++package org.openremote.agent.protocol.mqtt;++import javax.net.ssl.TrustManager;+import javax.net.ssl.TrustManagerFactory;+import javax.net.ssl.TrustManagerFactorySpi;+import javax.net.ssl.X509TrustManager;+import java.security.KeyStore;+import java.security.KeyStoreException;+import java.security.Provider;+import java.security.cert.CertificateException;+import java.security.cert.X509Certificate;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.List;++public class CustomX509TrustManagerFactorySpi extends TrustManagerFactorySpi {++ private final KeyStore[] keyStores;+ private final X509TrustManager trustManager;++ public CustomX509TrustManagerFactorySpi(KeyStore... keyStores) throws KeyStoreException {+ this.keyStores = keyStores;+ this.trustManager = createTrustManager();+ }++ @Override+ protected void engineInit(KeyStore keyStore) throws KeyStoreException {+ // Do nothing, since we have already initialized the SPI from the above constructor, and we don't want to+ // overwrite the object's fields.+ }++ @Override+ protected void engineInit(javax.net.ssl.ManagerFactoryParameters spec) {+ throw new UnsupportedOperationException("ManagerFactoryParameters not supported");+ }++ @Override+ protected TrustManager[] engineGetTrustManagers() {+ return new TrustManager[] { trustManager };+ }++ private X509TrustManager createTrustManager() throws KeyStoreException {+ try {+ if (keyStores == null) {+ throw new KeyStoreException("KeyStores not initialized");+ }+ List<X509TrustManager> trustManagerList = new ArrayList<>();+ for (KeyStore keyStore : keyStores) {+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());+ tmf.init(keyStore);+ for (TrustManager tm : tmf.getTrustManagers()) {+ if (tm instanceof X509TrustManager) {+ trustManagerList.add((X509TrustManager) tm);+ }+ }+ }+ return new CustomX509TrustManager(trustManagerList.toArray(new X509TrustManager[0]));+ } catch (Exception e) {+ throw new KeyStoreException("Error creating CustomX509TrustManager", e);+ }+ }++ public static class CustomX509TrustManager implements X509TrustManager {++ private final X509TrustManager[] trustManagers;++ public CustomX509TrustManager(X509TrustManager... trustManagers) {+ this.trustManagers = trustManagers;+ }++ private X509Certificate[] mergeCertificates() {+ ArrayList<X509Certificate> resultingCerts = new ArrayList<>();+ for (X509TrustManager tm : trustManagers) {+ resultingCerts.addAll(Arrays.asList(tm.getAcceptedIssuers()));+ }+ return resultingCerts.toArray(new X509Certificate[0]);+ }++ @Override+ public X509Certificate[] getAcceptedIssuers() {+ return mergeCertificates();+ }++ @Override+ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {+ for (X509TrustManager tm : trustManagers) {+ try {+ tm.checkServerTrusted(chain, authType);+ return;+ } catch (CertificateException ignored) {+ // continue to the next trust manager+ }+ }+ // If none of the trust managers trust the certificate chain, throw an exception+ throw new CertificateException("None of the trust managers trust this certificate chain");+ }++ @Override+ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {+ for (X509TrustManager tm : trustManagers) {+ try {+ tm.checkClientTrusted(chain, authType);+ return;+ } catch (CertificateException e) {+ // continue to the next trust manager+ }+ }+ // If none of the trust managers trust the certificate chain, throw an exception+ throw new CertificateException("None of the trust managers trust this certificate chain");+ }+ }++ // Register the provider+ public static class CustomProvider extends Provider {+ public CustomProvider() {+ super("CustomX509TrustManagerFactory", 1.0, "Custom X509 TrustManager Factory");+ put("TrustManagerFactory.CustomX509TrustManagerFactory", this.getClass().getName());+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.javaindex b82d28cbc..7adba13b1 100644--- a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.java+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.java@@ -35,6 +35,7 @@ public class MQTTAgent extends IOAgent<MQTTAgent, MQTTProtocol, MQTTAgentLink> {public static final AttributeDescriptor<Integer> PORT = Agent.PORT.withOptional(false);public static final AttributeDescriptor<String> CLIENT_ID = new AttributeDescriptor<>("clientId", ValueType.TEXT);public static final AttributeDescriptor<Boolean> SECURE_MODE = new AttributeDescriptor<>("secureMode", ValueType.BOOLEAN);+ public static final AttributeDescriptor<String> CLIENT_CERTIFICATE_ALIAS = new AttributeDescriptor<>("certificateAlias", ValueType.TEXT);public static final AttributeDescriptor<Boolean> RESUME_SESSION = new AttributeDescriptor<>("resumeSession", ValueType.BOOLEAN);public static final AttributeDescriptor<Boolean> WEBSOCKET_MODE = new AttributeDescriptor<>("websocketMode", ValueType.BOOLEAN);public static final AttributeDescriptor<String> WEBSOCKET_PATH = new AttributeDescriptor<>("websocketPath", ValueType.TEXT);@@ -80,6 +81,15 @@ public class MQTTAgent extends IOAgent<MQTTAgent, MQTTProtocol, MQTTAgentLink> {return this;}+ public Optional<String> getCertificateAlias() {+ return getAttributes().getValue(CLIENT_CERTIFICATE_ALIAS);+ }++ public MQTTAgent setCertificateAlias(String certificateAlias) {+ getAttributes().getOrCreate(CLIENT_CERTIFICATE_ALIAS).setValue(certificateAlias);+ return this;+ }+public Optional<Boolean> isWebsocketMode() {return getAttributes().getValue(WEBSOCKET_MODE);}diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.javaindex 563d4526d..e8235a361 100644--- a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.java@@ -20,6 +20,8 @@package org.openremote.agent.protocol.mqtt;import org.apache.http.client.utils.URIBuilder;+import org.openremote.model.Container;+import org.openremote.model.security.KeyStoreService;import org.openremote.model.util.UniqueIdentifierGenerator;import org.openremote.model.attribute.Attribute;import org.openremote.model.attribute.AttributeEvent;@@ -27,14 +29,14 @@ import org.openremote.model.attribute.AttributeRef;import org.openremote.model.syslog.SyslogCategory;import org.openremote.model.util.ValueUtil;+import javax.net.ssl.*;import java.net.URI;-import java.util.HashMap;-import java.util.Map;-import java.util.Optional;+import java.util.*;import java.util.function.Consumer;import java.util.logging.Logger;import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;+import static org.openremote.model.syslog.SyslogCategory.getLogger;public class MQTTProtocol extends AbstractMQTTClientProtocol<MQTTProtocol, MQTTAgent, String, MQTT_IOClient, MQTTAgentLink> {@@ -42,6 +44,8 @@ public class MQTTProtocol extends AbstractMQTTClientProtocol<MQTTProtocol, MQTTApublic static final String PROTOCOL_DISPLAY_NAME = "MQTT Client";protected final Map<AttributeRef, Consumer<MQTTMessage<String>>> protocolMessageConsumers = new HashMap<>();+ protected KeyStoreService keyStoreService;+protected MQTTProtocol(MQTTAgent agent) {super(agent);}@@ -57,6 +61,13 @@ public class MQTTProtocol extends AbstractMQTTClientProtocol<MQTTProtocol, MQTTA});}+ @Override+ protected void doStart(Container container) throws Exception {+ keyStoreService = container.getService(KeyStoreService.class);+ if (keyStoreService == null) throw new Exception("Couldn't load KeyStoreService");+ super.doStart(container);+ }+@Overrideprotected void doUnlinkAttribute(String assetId, Attribute<?> attribute, MQTTAgentLink agentLink) {agentLink.getSubscriptionTopic().ifPresent(topic -> {@@ -107,7 +118,17 @@ public class MQTTProtocol extends AbstractMQTTClientProtocol<MQTTProtocol, MQTTAlastWill = new MQTTLastWill(topic, payload, retain);}- return new MQTT_IOClient(agent.getClientId().orElseGet(UniqueIdentifierGenerator::generateId), host, port, agent.isSecureMode().orElse(false), !agent.isResumeSession().orElse(false), agent.getUsernamePassword().orElse(null), websocketURI, lastWill);+ //It's fine if they're null, they're not going to be used when creating the client+ TrustManagerFactory trustManagerFactory = null;+ KeyManagerFactory keyManagerFactory = null;+ if(agent.isSecureMode().orElse(false)){+ trustManagerFactory = keyStoreService.getTrustManagerFactory();+ if(agent.getCertificateAlias().isPresent()){+ keyManagerFactory = keyStoreService.getKeyManagerFactory(agent.getRealm()+"."+agent.getCertificateAlias().orElseThrow());+ }+ }++ return new MQTT_IOClient(agent.getClientId().orElseGet(UniqueIdentifierGenerator::generateId), host, port, agent.isSecureMode().orElse(false), !agent.isResumeSession().orElse(false), agent.getUsernamePassword().orElse(null), websocketURI, lastWill, keyManagerFactory, trustManagerFactory);}@Overridediff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTT_IOClient.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTT_IOClient.javaindex cca96208f..21d8212a3 100644--- a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTT_IOClient.java+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTT_IOClient.java@@ -21,17 +21,22 @@ package org.openremote.agent.protocol.mqtt;import org.openremote.model.auth.UsernamePassword;+import javax.net.ssl.KeyManagerFactory;+import javax.net.ssl.TrustManagerFactory;import java.net.URI;import java.nio.charset.StandardCharsets;public class MQTT_IOClient extends AbstractMQTT_IOClient<String> {- public MQTT_IOClient(String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI, MQTTLastWill lastWill) {- super(host, port, secure, cleanSession, usernamePassword, websocketURI, lastWill);+ public MQTT_IOClient(String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI, MQTTLastWill lastWill, KeyManagerFactory keyManagerFactory, TrustManagerFactory trustManagerFactory) {+ super(host, port, secure, cleanSession, usernamePassword, websocketURI, lastWill, keyManagerFactory, trustManagerFactory);}+ public MQTT_IOClient(String clientId, String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI, MQTTLastWill lastWill, KeyManagerFactory keyManagerFactory, TrustManagerFactory trustManagerFactory) {+ super(clientId, host, port, secure, cleanSession, usernamePassword, websocketURI, lastWill, keyManagerFactory, trustManagerFactory );+ }public MQTT_IOClient(String clientId, String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI, MQTTLastWill lastWill) {- super(clientId, host, port, secure, cleanSession, usernamePassword, websocketURI, lastWill);+ super(clientId, host, port, secure, cleanSession, usernamePassword, websocketURI, lastWill, null, null);}@Overridediff --git a/manager/src/main/java/org/openremote/manager/security/KeyStoreServiceImpl.java b/manager/src/main/java/org/openremote/manager/security/KeyStoreServiceImpl.javanew file mode 100644index 000000000..428933c05--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/security/KeyStoreServiceImpl.java@@ -0,0 +1,219 @@+/*+ * Copyright 2024, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */++package org.openremote.manager.security;++import org.openremote.agent.protocol.mqtt.CustomKeyManagerFactory;+import org.openremote.agent.protocol.mqtt.CustomX509TrustManagerFactory;+import org.openremote.container.persistence.PersistenceService;+import org.openremote.model.Container;+import org.openremote.model.security.KeyStoreService;++import javax.net.ssl.KeyManagerFactory;+import javax.net.ssl.TrustManagerFactory;+import java.io.*;+import java.nio.file.Path;+import java.nio.file.Paths;+import java.security.KeyStore;+import java.util.logging.Logger;+import java.util.Optional;++import static org.openremote.container.util.MapAccess.getString;++/**+ * <p>+ * This service is used for retrieving, creating, or editing KeyStore (and TrustStore) files.+ * </p><p>+ * Currently the KeyStores are stored in the Storage directory of OpenRemote, which is usually volumed and persisted.+ * </p><p>+ * Each realm is allocated 2 KeyStores; A Client KeyStore, which is used for storing key-pairs that are used by+ * clients (be that as an Agent or as a plain client), and a TrustStore, which contains trusted certificates, usually SSL+ * certificates. To ensure both security and extensibility, both the default and predefined TrustStores are used to find+ * the correct certificates.+ * </p>+ */+public class KeyStoreServiceImpl implements KeyStoreService {++ protected PersistenceService persistenceService;+ protected ManagerIdentityService identityService;++ private KeyStore keyStore = null;+ private KeyStore trustStore = null;++ private static final String OR_SSL_CLIENT_KEYSTORE_FILE = "OR_SSL_CLIENT_KEYSTORE_FILE";+ private static final String OR_SSL_CLIENT_TRUSTSTORE_FILE = "OR_SSL_CLIENT_TRUSTSTORE_FILE";++ private static final String OR_SSL_CLIENT_KEYSTORE_PASSWORD = "OR_SSL_CLIENT_KEYSTORE_PASSWORD";+ private static final String OR_SSL_CLIENT_TRUSTSTORE_PASSWORD = "OR_SSL_CLIENT_TRUSTSTORE_PASSWORD";++ private static final String OR_KEYSTORE_PASSWORD = "OR_KEYSTORE_PASSWORD";++ protected Path keyStorePath;+ protected Path trustStorePath;++ private String keyStorePassword;++ @Override+ public int getPriority() {+ return ManagerIdentityService.PRIORITY + 10;+ }++ @Override+ public void init(Container container) throws Exception {+ persistenceService = container.getService(PersistenceService.class);+ identityService = container.getService(ManagerIdentityService.class);++ String defaultPassword = getString(container.getConfig(), "OR_ADMIN_PASSWORD", "secret");++ keyStorePassword = getString(container.getConfig(), OR_KEYSTORE_PASSWORD, defaultPassword);+ }++ @Override+ public void start(Container container) throws Exception {++ String keyStoreEnv = getString(container.getConfig(), OR_SSL_CLIENT_KEYSTORE_FILE, null);+ String trustStoreEnv = getString(container.getConfig(), OR_SSL_CLIENT_TRUSTSTORE_FILE, null);++ Optional<Path> keyStorePath = keyStoreEnv != null ? Optional.of(Paths.get(keyStoreEnv)) : Optional.empty();+ Optional<Path> trustStorePath = trustStoreEnv != null ? Optional.of(Paths.get(trustStoreEnv)) : Optional.empty();++ String keyStorePassword = getString(container.getConfig(), OR_SSL_CLIENT_KEYSTORE_PASSWORD, String.valueOf(getKeyStorePassword()));+ String trustStorePassword = getString(container.getConfig(), OR_SSL_CLIENT_TRUSTSTORE_PASSWORD, String.valueOf(getKeyStorePassword()));+++ if (keyStorePath.isPresent()) {+ this.keyStore = KeyStore.getInstance(keyStorePath.get().toFile(), keyStorePassword.toCharArray());+ } else {+ Path defaultKeyStorePath = persistenceService.resolvePath(Paths.get("keystores").resolve("client_keystore.p12"));+ if (new File(defaultKeyStorePath.toUri()).exists()) {+ this.keyStorePath = defaultKeyStorePath;+ this.keyStore = KeyStore.getInstance(new File(defaultKeyStorePath.toUri()), getKeyStorePassword());+ } else {+ this.keyStore = createKeyStore(defaultKeyStorePath);+ }++ this.keyStorePath = defaultKeyStorePath;+ }++ if (trustStorePath.isPresent()) {+ this.trustStore = KeyStore.getInstance(trustStorePath.get().toFile(), trustStorePassword.toCharArray());+ } else {+ Path defaultTrustStorePath = persistenceService.resolvePath(Paths.get("keystores").resolve("client_truststore.p12"));+ if (new File(defaultTrustStorePath.toUri()).exists()) {+ this.trustStorePath = defaultTrustStorePath;+ this.trustStore = KeyStore.getInstance(new File(defaultTrustStorePath.toUri()), getKeyStorePassword());+ } else {+ this.trustStore = createKeyStore(defaultTrustStorePath);+ }+ this.trustStorePath = defaultTrustStorePath;+ }+ }++ private KeyStore getKeyStore() {+ try {+ return KeyStore.getInstance(this.keyStorePath.toAbsolutePath().toFile(), getKeyStorePassword());+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }++ private KeyStore getTrustStore() {+ try {+ return KeyStore.getInstance(this.trustStorePath.toAbsolutePath().toFile(), getKeyStorePassword());+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }++ private void storeKeyStore(KeyStore keystore) {+ try {+ this.keyStore = keystore;+ keystore.store(new FileOutputStream(this.keyStorePath.toFile()), getKeyStorePassword());+ } catch (Exception saveException) {+ getLogger().severe("Couldn't store KeyStore to Storage! " + saveException.getMessage());+ }+ }++ private void storeTrustStore(KeyStore truststore) {+ try {+ this.trustStore = truststore;+ truststore.store(new FileOutputStream(this.trustStorePath.toFile()), getKeyStorePassword());+ } catch (Exception saveException) {+ getLogger().severe("Couldn't store TrustStore to Storage! " + saveException.getMessage());+ }+ }++ private char[] getKeyStorePassword() {+ return this.keyStorePassword.toCharArray();+ }++ @Override+ public KeyManagerFactory getKeyManagerFactory(String alias) throws Exception {+ KeyManagerFactory keyManagerFactory = new CustomKeyManagerFactory(alias);+ try {+ keyManagerFactory.init(this.keyStore, getKeyStorePassword());+ } catch (Exception e) {+ throw new Exception("Could not retrieve KeyManagerFactory: " + e.getMessage());+ }++ return keyManagerFactory;+ }++ @Override+ public TrustManagerFactory getTrustManagerFactory() throws Exception {++ CustomX509TrustManagerFactory tmf = new CustomX509TrustManagerFactory(this.trustStore, (KeyStore) null);+ try {+ tmf.init((KeyStore) null);+ } catch (Exception e) {+ throw new Exception("Could not retrieve KeyManagerFactory: " + e.getMessage());+ }++ return tmf;+ }++ protected KeyStore createKeyStore(Path path) throws Exception {+ KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());+ keystore.load(null, getKeyStorePassword());+ File keyStoreFile = path.toAbsolutePath().toFile();+ if (keyStoreFile.getParentFile() != null && !keyStoreFile.getParentFile().exists()) {+ keyStoreFile.getParentFile().mkdirs();+ }+ keyStoreFile.createNewFile();++ // Save the newly created KeyStore+ try (OutputStream os = new FileOutputStream(keyStoreFile)) {+ keystore.store(os, getKeyStorePassword());+ } catch (Exception saveException) {+ getLogger().severe("Couldn't store KeyStore to Storage! " + saveException.getMessage());+ throw saveException;+ }+ return keystore;+ }++ @Override+ public void stop(Container container) throws Exception {++ }++ private Logger getLogger() {+ return LOG;+ }+}diff --git a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerServiceindex 15148ac95..ed76c9c6a 100644--- a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService+++ b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService@@ -34,3 +34,4 @@ org.openremote.manager.security.AuthorisationServiceorg.openremote.manager.app.ConfigurationServiceorg.openremote.manager.asset.ForecastServiceorg.openremote.manager.setup.KeycloakInitService+org.openremote.manager.security.KeyStoreServiceImpldiff --git a/model/src/main/java/org/openremote/model/security/KeyStoreService.java b/model/src/main/java/org/openremote/model/security/KeyStoreService.javanew file mode 100644index 000000000..3044b13be--- /dev/null+++ b/model/src/main/java/org/openremote/model/security/KeyStoreService.java@@ -0,0 +1,34 @@+/*+ * Copyright 2024, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */++package org.openremote.model.security;++import org.openremote.model.ContainerService;++import javax.net.ssl.KeyManagerFactory;+import javax.net.ssl.TrustManagerFactory;+import java.util.logging.Logger;++public interface KeyStoreService extends ContainerService {+ Logger LOG = Logger.getLogger(KeyStoreService.class.getName());++ KeyManagerFactory getKeyManagerFactory(String alias) throws Exception;+ TrustManagerFactory getTrustManagerFactory() throws Exception;+}diff --git a/test/src/test/groovy/org/openremote/test/protocol/mqtt/MQTTClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/mqtt/MQTTClientProtocolTest.groovyindex e691b31c4..63ec11e9e 100644--- a/test/src/test/groovy/org/openremote/test/protocol/mqtt/MQTTClientProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/mqtt/MQTTClientProtocolTest.groovy@@ -19,17 +19,28 @@*/package org.openremote.test.protocol.mqtt+import org.bouncycastle.asn1.x500.X500Name+import org.bouncycastle.cert.X509v3CertificateBuilder+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder+import org.bouncycastle.operator.ContentSigner+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder+import org.bouncycastle.pkcs.PKCS10CertificationRequest+import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder+import org.bouncycastle.util.io.pem.PemObject+import org.bouncycastle.util.io.pem.PemWriter+import org.junit.AssumptionViolatedExceptionimport org.openremote.agent.protocol.mqtt.MQTTAgentimport org.openremote.agent.protocol.mqtt.MQTTAgentLinkimport org.openremote.agent.protocol.mqtt.MQTTProtocolimport org.openremote.agent.protocol.simulator.SimulatorProtocol-import org.openremote.model.util.UniqueIdentifierGeneratorimport org.openremote.manager.agent.AgentServiceimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.event.ClientEventServiceimport org.openremote.manager.mqtt.DefaultMQTTHandlerimport org.openremote.manager.mqtt.MQTTBrokerService+import org.openremote.manager.security.KeyStoreServiceImplimport org.openremote.manager.setup.SetupServiceimport org.openremote.model.Constantsimport org.openremote.model.asset.agent.Agent@@ -39,12 +50,24 @@ import org.openremote.model.attribute.Attributeimport org.openremote.model.attribute.AttributeEventimport org.openremote.model.attribute.MetaItemimport org.openremote.model.auth.UsernamePassword-import org.openremote.test.ManagerContainerTrait+import org.openremote.model.util.UniqueIdentifierGeneratorimport org.openremote.setup.integration.KeycloakTestSetupimport org.openremote.setup.integration.ManagerTestSetup+import org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions+import java.net.http.HttpClient+import java.net.http.HttpRequest+import java.net.http.HttpResponse+import java.nio.charset.StandardCharsets+import java.security.KeyPairGenerator+import java.security.KeyStore+import java.security.PrivateKey+import java.security.cert.Certificate+import java.security.cert.CertificateFactory+import java.security.cert.X509Certificate+import static org.openremote.manager.mqtt.MQTTBrokerService.getConnectionIDStringimport static org.openremote.model.value.MetaItemType.AGENT_LINKimport static org.openremote.model.value.ValueType.NUMBER@@ -139,5 +162,197 @@ class MQTTClientProtocolTest extends Specification implements ManagerContainerTrasset = assetStorageService.find(asset.getId(), true)assert asset.getAttribute("readWriteTargetTemp").flatMap{it.getValue()}.orElse(null) == 19.5d}+++ }+++ /**+ * This test is not fully done right now, as a non-internet-requiring test would require mTLS functionality within the+ * OpenRemote broker, something that will eventually be done.+ *+ * For now, we will use test.mosquitto.org, an open broker that is provided by the creators of mosquitto. They provide+ * multiple ways of accessing the broker, including one that requires a client certificate and TLS. Using that broker,+ * we will test the mTLS and TLS functionalities.+ *+ * To access the broker, we need them to sign our certificate. To do that, we can request+ *+ * If the test cannot reach the host, then the test is passed.+ * */+ @SuppressWarnings("GroovyAccessibility")+ def "Check MQTT client protocol mTLS support"() {++ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 100, delay: 0.2)++ and: "External connectivity has been assured"+ try {+ assert new Socket("test.mosquitto.org", 8884) != null+ assert new Socket("test.mosquitto.org", 443) != null+ } catch (Exception e) {+ throw new AssumptionViolatedException("No connectivity to external hosts, skip test");+ }++ and: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def keyStoreService = container.getService(KeyStoreServiceImpl.class)+ def mqttHost = "test.mosquitto.org"+ def mqttPort = 8884+++ def keystorePassword = "secret"+ def keyPassword = "secret"++ def aliasName = "testalias"+ def keyAlias = Constants.MASTER_REALM + "." + aliasName+++ KeyStore clientKeystore = keyStoreService.getKeyStore()+ KeyStore clientTruststore = keyStoreService.getTrustStore()++ // Create keystore and keypair+ clientKeystore = createKeystore(clientKeystore, keyAlias, keyPassword)++ // Get SSL certificate of test.mosquitto.org:8884+ def cert = getCertificate("https://test.mosquitto.org/ssl/mosquitto.org.crt")++ // Import X509 Certificate into the truststore+ clientTruststore.setCertificateEntry(keyAlias, cert)++ // Generate the CSR, to be sent to the Mosquitto server for signing, URLEncode it+ String csrPem = generateCSR(clientKeystore, keyAlias, keyPassword)+ csrPem = URLEncoder.encode(csrPem, StandardCharsets.UTF_8.toString())++ //Send the CSR to their webserver that automatically signs the certificate+ HttpClient client = HttpClient.newHttpClient()+ HttpRequest request = HttpRequest.newBuilder()+ .uri(new URI("https://test.mosquitto.org/ssl/index.php"))+ .header("Content-Type", "application/x-www-form-urlencoded")+ .POST(HttpRequest.BodyPublishers.ofString("csr="+csrPem))+ .build()++ // Take the response,+ HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString())++ String signedCertPem = response.body()++ if (response.statusCode() != 200) throw new Exception("Signing request failed")++ clientKeystore = importCertificate(clientKeystore, keyAlias, signedCertPem, keystorePassword.toCharArray())++ keyStoreService.storeKeyStore(clientKeystore)+ keyStoreService.storeTrustStore(clientTruststore)++ when: "an MQTT client agent is created to connect to this tests manager"+ def clientId = UniqueIdentifierGenerator.generateId()+ def agent = new MQTTAgent("Test agent")+ .setRealm(Constants.MASTER_REALM)+ .setClientId(clientId)+ .setPort(mqttPort)+ .setHost(mqttHost)+ .setSecureMode(true)+ .setCertificateAlias(aliasName)+// .setUsernamePassword(new UsernamePassword(keycloakTestSetup.realmBuilding.name + ":" + keycloakTestSetup.serviceUser.username, keycloakTestSetup.serviceUser.secret))+ and: "the agent is added to the asset service"+ agent = assetStorageService.merge(agent)++ then: "the protocol should authenticate and the agent status should become CONNECTED"+ conditions.eventually {+ agent = assetStorageService.find(agent.id, Agent.class)+ assert agent.getAgentStatus().orElse(null) == ConnectionStatus.CONNECTED+ }++ when: "the agent is connected, show the SSL certificates used"+ def protocol = agent.getProtocolInstance() as MQTTProtocol+ then: "test"+ protocol.properties+ }+++ KeyStore createKeystore(KeyStore keyStore, String alias, String keyPassword) {+ // Create a new keypair+ KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA")+ keyGen.initialize(2048)+ def keyPair = keyGen.generateKeyPair()++ /// Generate a self-signed certificate+ X500Name subject = new X500Name("CN=mTLS Test,OU=OpenRemote,O=OpenRemote,L=Eindhoven,ST=Noord-Brabant,C=NL")+ long now = System.currentTimeMillis()+ Date startDate = new Date(now)+ Date endDate = new Date(now + 365 * 86400000L)+ X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(+ subject,+ BigInteger.valueOf(now),+ startDate,+ endDate,+ subject,+ keyPair.getPublic()+ )+++ ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").build(keyPair.getPrivate())+ X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner))++ keyStore.setKeyEntry(alias, keyPair.getPrivate(), keyPassword.toCharArray(), new X509Certificate[] { cert })++ // Store the keystore+ return keyStore+ }++ X509Certificate getCertificate(String url) {+ URL pemUrl = new URL(url)+ CertificateFactory cf = CertificateFactory.getInstance("X.509")+ X509Certificate cert = (X509Certificate) cf.generateCertificate(pemUrl.openStream())++ return cert+ }++ String generateCSR(KeyStore keyStore, String alias, String keyPassword) {++ // Retrieve the Private Key and Certificate+ PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, keyPassword.toCharArray())+ Certificate cert = keyStore.getCertificate(alias)+ X509Certificate x509Cert = (X509Certificate) cert++ // Build X500Name from the Certificate's Subject+ X500Name x500Name = new X500Name(x509Cert.getSubjectX500Principal().getName())++ // Build ContentSigner+ ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(privateKey)++ // Build PKCS10CertificationRequest+ JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Name, x509Cert.getPublicKey())+ PKCS10CertificationRequest csr = csrBuilder.build(signer)++ String csrPEM+ try (StringWriter stringWriter = new StringWriter()+ PemWriter pemWriter = new PemWriter(stringWriter)) {+ pemWriter.writeObject(new PemObject("CERTIFICATE REQUEST", csr.getEncoded()))+ pemWriter.flush()+ csrPEM = stringWriter.toString()++ }+ return csrPEM+ }++ KeyStore importCertificate(KeyStore keyStore, String alias, String signedCertPem, char[] keystorePassword) {+ try {+ // Convert PEM to X509Certificate+ byte[] certBytes = Base64.decoder.decode(signedCertPem+ .replace("-----BEGIN CERTIFICATE-----", "")+ .replace("-----END CERTIFICATE-----", "")+ .replaceAll("\\s", ""))+ CertificateFactory certFactory = CertificateFactory.getInstance("X.509")+ X509Certificate signedCert = certFactory.generateCertificate(new ByteArrayInputStream(certBytes))++ // Set the certificate chain+ Certificate[] certChain = [signedCert] as Certificate[]+ keyStore.setKeyEntry(alias, keyStore.getKey(alias, keystorePassword), keystorePassword, certChain)++ return keyStore+ } catch (Exception e) {+ e.printStackTrace()+ }}}