Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Fix MQTT X.509 provisioning impersonation

axelixyef497cca0d02
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java
index 6fdab8871..7d368e711 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java
@@ -23,15 +23,23 @@ import static org.openremote.container.persistence.PersistenceService.isPersiste
import static org.openremote.model.Constants.RESTRICTED_USER_REALM_ROLE;
import static org.openremote.model.syslog.SyslogCategory.API;
+import com.google.common.base.Ticker;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.MqttQoS;
import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.SecureRandom;
+import java.security.Signature;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
+import java.security.interfaces.EdECKey;
+import java.time.Duration;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -66,6 +74,49 @@ import org.openremote.model.util.ValueUtil;
* This {@link MQTTHandler} is responsible for provisioning service users and assets and
* authenticating the client against the configured {@link
* org.openremote.model.provisioning.ProvisioningConfig}s.
+ *
+ * <h2>X.509 provisioning</h2>
+ *
+ * <p>A public certificate is not a credential, so a client must prove it holds the certificate's
+ * private key on the same MQTT connection, for both initial enrollment and every reconnect:
+ *
+ * <ol>
+ * <li>Subscribe to {@code provisioning/{CN}/response}.
+ * <li>Publish an {@link X509ProvisioningChallengeRequestMessage} to {@code
+ * provisioning/{CN}/request}; the certificate is validated and an {@link
+ * X509ProvisioningChallengeResponseMessage} is returned.
+ * <li>Publish an {@link X509ProvisioningMessage} with the certificate and the signed challenge;
+ * only once the signature verifies is the service user and asset looked up or created and the
+ * connection authenticated.
+ * </ol>
+ *
+ * <p>A challenge is a protocol prefix, the request topic and a random 256-bit nonce. It is bound to
+ * the {@link RemotingConnection}, topic and certificate, expires after 60 seconds, is replaced by a
+ * new request and is consumed by any verification attempt, so a proof can never be replayed. The
+ * signature algorithm follows the certificate's key: SHA256withRSA, SHA256withECDSA for every
+ * curve, Ed25519 or Ed448; RSASSA-PSS keys are rejected. Certificate-only {@code x509} requests are
+ * rejected with {@code UNAUTHORIZED}; there is no fallback.
+ *
+ * <h3>Response topic ownership</h3>
+ *
+ * <p>Responses go to a device-wide topic, so whichever connection receives them must be the one
+ * making the requests, otherwise an attacker could have the real device sign the attacker's
+ * challenge or push errors into its exchange:
+ *
+ * <ul>
+ * <li>{@link #canSubscribe} claims the response topic atomically, and a connection may own only
+ * one, so a single connection cannot lock many devices out of provisioning.
+ * <li>{@link #canPublish} only lets the owner publish to the matching request topic.
+ * <li>Requests are processed from a queue after {@link #canPublish} authorized them, so ownership
+ * is checked again before processing, and a message whose connection has lost the topic is
+ * dropped without a reply.
+ * <li>Artemis runs the disconnect callbacks before it closes the transport, so cleanup marks the
+ * connection first and a concurrent {@link #canSubscribe} backs out of its claim.
+ * </ul>
+ *
+ * <p>The client-facing protocol, including what a device must check before signing, is documented
+ * at <a href="https://docs.openremote.io/docs/user-guide/gateways-and-devices/auto-provisioning">
+ * Auto provisioning devices and users</a>.
*/
public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
@@ -126,9 +177,54 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
protected final ConcurrentMap<Long, Set<RemotingConnection>>
provisioningConfigAuthenticatedConnectionMap = new ConcurrentHashMap<>();
protected Timer provisioningTimer;
- protected final Map<String, RemotingConnection> responseSubscribedConnections =
+
+ /**
+ * The single source of truth for which connection owns a provisioning response topic; ownership
+ * is claimed atomically in {@link #canSubscribe} and is required to publish the matching request
+ * topic.
+ */
+ protected final ConcurrentMap<String, RemotingConnection> responseTopicOwners =
+ new ConcurrentHashMap<>();
+
+ /**
+ * Reverse index of {@link #responseTopicOwners} so disconnects don't scan the whole map. A
+ * connection may own at most one response topic, see {@link #canSubscribe}.
+ */
+ protected final ConcurrentMap<RemotingConnection, String> connectionResponseTopics =
new ConcurrentHashMap<>();
+ /**
+ * Connections whose disconnect cleanup has started. Artemis calls the disconnect callbacks before
+ * it closes the transport, so a subscribe being authorized at the same time cannot tell from the
+ * transport that the connection is going; {@link #canSubscribe} checks this after claiming and
+ * backs out. Weak keys let entries go once Artemis drops the connection.
+ */
+ protected final Set<RemotingConnection> closedConnections =
+ Collections.newSetFromMap(
+ CacheBuilder.newBuilder().weakKeys().<RemotingConnection, Boolean>build().asMap());
+
+ protected final SecureRandom challengeRandom = new SecureRandom();
+ protected final Cache<RemotingConnection, X509Challenge> provisioningChallenges;
+
+ protected record X509Challenge(
+ String topic, X509Certificate certificate, String challenge, String algorithm) {}
+
+ public UserAssetProvisioningMQTTHandler() {
+ this(Ticker.systemTicker());
+ }
+
+ protected UserAssetProvisioningMQTTHandler(Ticker ticker) {
+ provisioningChallenges =
+ CacheBuilder.newBuilder()
+ .weakKeys()
+ // Challenges live for at most 60s and are dropped with their connection; the size cap
+ // only bounds memory under a burst, where an evicted device simply requests a new one.
+ .maximumSize(10000)
+ .expireAfterWrite(Duration.ofSeconds(60))
+ .ticker(ticker)
+ .build();
+ }
+
@Override
public void init(Container container, Configuration serverConfiguration) throws Exception {
super.init(container, serverConfiguration);
@@ -236,34 +332,84 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
&& !TOKEN_MULTI_LEVEL_WILDCARD.equals(topicTokenIndexToString(topic, 1))
&& !TOKEN_SINGLE_LEVEL_WILDCARD.equals(topicTokenIndexToString(topic, 1));
- if (allowed) {
- // Only allow if there is no existing subscription for this topic
- RemotingConnection existingConnection = responseSubscribedConnections.get(topic.toString());
- if (existingConnection != null && existingConnection.getTransportConnection().isOpen()) {
- LOG.warning("Subscription already exists possible eavesdropping");
- allowed = false;
- }
+ if (!allowed) {
+ return false;
}
- return allowed;
+ String responseTopic = topic.toString();
+
+ // A provisioning client only ever needs its own response topic, so a connection may own one.
+ // Without this cap a single anonymous connection could claim the topics of many devices and
+ // lock them all out of provisioning until it disconnects.
+ String existingTopic = connectionResponseTopics.putIfAbsent(connection, responseTopic);
+ if (existingTopic != null && !existingTopic.equals(responseTopic)) {
+ LOG.info(
+ "Connection already owns a provisioning response topic: existing="
+ + existingTopic
+ + ", requested="
+ + responseTopic
+ + ", "
+ + MQTTBrokerService.connectionToString(connection));
+ return false;
+ }
+
+ // Claim the response topic atomically during authorization. Otherwise two concurrent
+ // subscribers could both pass this check and receive each other's challenges and responses.
+ //
+ // The claim deliberately outlives a subscribe that Artemis fails after authorizing it; it is
+ // released by unsubscribe or disconnect. Deferring it to onSubscribe would reopen the window
+ // above, and the leftover claim only keeps this one topic from other connections while the
+ // connection that asked for it stays open. That connection can simply retry, as re-claiming
+ // a topic it already owns is allowed.
+ RemotingConnection owner =
+ responseTopicOwners.compute(
+ responseTopic,
+ (t, existing) ->
+ existing == null || existing == connection || !isOpen(existing)
+ ? connection
+ : existing);
+
+ if (owner != connection) {
+ // Give back the slot reserved above so the connection can still claim its own topic
+ connectionResponseTopics.remove(connection, responseTopic);
+ LOG.warning("Subscription already exists possible eavesdropping");
+ return false;
+ }
+
+ // If disconnect cleanup started while claiming, it may already have run and would never remove
+ // these entries, leaking the connection; clearConnectionState marks the connection before it
+ // removes anything, so either this check sees the mark or the cleanup sees the claims.
+ if (closedConnections.contains(connection)) {
+ releaseResponseTopic(connection, responseTopic);
+ return false;
+ }
+
+ return true;
}
@Override
public void onSubscribe(RemotingConnection connection, Topic topic) {
- responseSubscribedConnections.put(topic.toString(), connection);
+ // Ownership was already claimed in canSubscribe, which is the only place it is granted; see
+ // there for why a failed subscribe keeps its claim
}
@Override
public void onUnsubscribe(RemotingConnection connection, Topic topic) {
- responseSubscribedConnections.computeIfPresent(
- topic.toString(),
- (t, existingConnection) -> {
- // Don't remove the existing entry if it is for a different connection; this is a
- // possibility if a client
- // disconnects and quickly reconnects as we have no guaranteed ordering of
- // subscribe/unsubscribe calls
- return existingConnection == connection ? null : existingConnection;
- });
+ releaseResponseTopic(connection, topic.toString());
+ }
+
+ protected static boolean isOpen(RemotingConnection connection) {
+ return connection.getTransportConnection() != null
+ && connection.getTransportConnection().isOpen();
+ }
+
+ /**
+ * Releases the topic only if this connection still owns it; a client that disconnects and quickly
+ * reconnects has no guaranteed ordering of subscribe/unsubscribe calls.
+ */
+ protected void releaseResponseTopic(RemotingConnection connection, String responseTopic) {
+ responseTopicOwners.remove(responseTopic, connection);
+ connectionResponseTopics.remove(connection, responseTopic);
}
@Override
@@ -278,9 +424,34 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
return false;
}
- return isRequestTopic(topic)
- && !TOKEN_MULTI_LEVEL_WILDCARD.equals(topicTokenIndexToString(topic, 1))
- && !TOKEN_SINGLE_LEVEL_WILDCARD.equals(topicTokenIndexToString(topic, 1));
+ if (!isRequestTopic(topic)
+ || TOKEN_MULTI_LEVEL_WILDCARD.equals(topicTokenIndexToString(topic, 1))
+ || TOKEN_SINGLE_LEVEL_WILDCARD.equals(topicTokenIndexToString(topic, 1))) {
+ return false;
+ }
+
+ // Requests and their responses are two halves of one exchange on a device wide topic pair, so
+ // only the connection that owns the response topic may publish requests. Without this an
+ // unauthorised client could push errors into a legitimate device's handshake, or make the
+ // manager do certificate validation work on messages it will never answer to that client.
+ if (!ownsResponseTopic(connection, topic)) {
+ LOG.fine(
+ () ->
+ "Connection does not own the provisioning response topic: topic="
+ + topic
+ + ", "
+ + MQTTBrokerService.connectionToString(connection));
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * The connection must be subscribed to {@code provisioning/{id}/response} to publish requests.
+ */
+ protected boolean ownsResponseTopic(RemotingConnection connection, Topic requestTopic) {
+ return responseTopicOwners.get(getResponseTopic(requestTopic)) == connection;
}
@Override
@@ -312,6 +483,7 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
@Override
public void onConnectionLost(RemotingConnection connection) {
+ clearConnectionState(connection);
provisioningConfigAuthenticatedConnectionMap
.values()
.forEach(
@@ -326,6 +498,7 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
@Override
public void onDisconnect(RemotingConnection connection) {
+ clearConnectionState(connection);
provisioningConfigAuthenticatedConnectionMap
.values()
.forEach(
@@ -360,9 +533,13 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
return;
}
- if (provisioningMessage instanceof X509ProvisioningMessage) {
- processX509ProvisioningMessage(
- connection, topic, (X509ProvisioningMessage) provisioningMessage);
+ switch (provisioningMessage) {
+ case X509ProvisioningChallengeRequestMessage message ->
+ processX509ProvisioningMessage(connection, topic, message.getCert(), null, true);
+ case X509ProvisioningMessage message ->
+ processX509ProvisioningMessage(
+ connection, topic, message.getCert(), message.getSignature(), false);
+ default -> {}
}
}
@@ -382,15 +559,39 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
return PROVISIONING_TOKEN + "/" + topicTokenIndexToString(topic, 1) + "/" + RESPONSE_TOKEN;
}
+ /**
+ * Handles both steps of the X.509 exchange; {@code challengeRequest} selects the first one. No
+ * lock is held here: the one use semantics of a challenge come from removing it atomically from
+ * {@link #provisioningChallenges}, and the provisioning work that follows involves Keycloak I/O
+ * that must not block the Artemis threads running the disconnect callbacks.
+ */
protected void processX509ProvisioningMessage(
- RemotingConnection connection, Topic topic, X509ProvisioningMessage provisioningMessage) {
+ RemotingConnection connection,
+ Topic topic,
+ String cert,
+ String signature,
+ boolean challengeRequest) {
LOG.fine(
() ->
"Processing X.509 provisioning message: "
+ MQTTBrokerService.connectionToString(connection));
- if (TextUtil.isNullOrEmpty(provisioningMessage.getCert())) {
+ // canPublish checked ownership when the message arrived, but it is processed later from a queue
+ // and the topic may have changed hands since. Drop it silently: any reply would go to the
+ // response topic of whichever connection owns it now.
+ if (!ownsResponseTopic(connection, topic)) {
+ LOG.fine(
+ () ->
+ "Dropping X.509 provisioning message as the connection no longer owns the response"
+ + " topic: topic="
+ + topic
+ + ", "
+ + MQTTBrokerService.connectionToString(connection));
+ return;
+ }
+
+ if (TextUtil.isNullOrEmpty(cert)) {
LOG.info(
"Certificate is missing from X509 provisioning message"
+ MQTTBrokerService.connectionToString(connection));
@@ -404,7 +605,7 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
// Parse client cert
X509Certificate clientCertificate;
try {
- clientCertificate = ProvisioningUtil.getX509Certificate(provisioningMessage.getCert());
+ clientCertificate = ProvisioningUtil.getX509Certificate(cert);
} catch (CertificateException e) {
LOG.log(
Level.INFO,
@@ -472,6 +673,21 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
return;
}
+ if (challengeRequest) {
+ issueX509Challenge(connection, topic, clientCertificate);
+ return;
+ }
+
+ // A CA-valid public certificate is not an authentication credential. Require a one-time proof
+ // on this connection before looking up or creating any user or asset, including on reconnect.
+ if (!verifyX509Proof(connection, topic, clientCertificate, signature)) {
+ publishMessage(
+ getResponseTopic(topic),
+ new ErrorResponseMessage(ErrorResponseMessage.Error.UNAUTHORIZED),
+ MqttQoS.AT_MOST_ONCE);
+ return;
+ }
+
String realm = matchingConfig.getRealm();
// Get/create service user
@@ -558,6 +774,96 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
getResponseTopic(topic), new SuccessResponseMessage(realm, asset), MqttQoS.AT_MOST_ONCE);
}
+ protected void issueX509Challenge(
+ RemotingConnection connection, Topic topic, X509Certificate certificate) {
+ provisioningChallenges.invalidate(connection);
+ // Responses use a device wide topic. Only its owning connection may request a challenge,
+ // otherwise an attacker could cause the legitimate subscriber to sign the attacker's challenge.
+ // canPublish and processX509ProvisioningMessage already check this; it is repeated right before
+ // the challenge is issued as ownership can still change during processing. Nothing is published
+ // on failure, as the response topic belongs to another connection.
+ if (!ownsResponseTopic(connection, topic)) {
+ LOG.fine(
+ () ->
+ "Not issuing X.509 challenge as the connection does not own the response topic: "
+ + MQTTBrokerService.connectionToString(connection));
+ return;
+ }
+
+ // Signature algorithms are chosen from the key algorithm as reported by the provider. EC keys
+ // always get SHA-256 whatever the curve, and keys that report as RSASSA-PSS are not supported
+ // and are rejected as UNAUTHORIZED.
+ String algorithm =
+ switch (certificate.getPublicKey().getAlgorithm()) {
+ case "RSA" -> "SHA256withRSA";
+ case "EC" -> "SHA256withECDSA";
+ case "EdDSA" -> ((EdECKey) certificate.getPublicKey()).getParams().getName();
+ case "Ed25519", "Ed448" -> certificate.getPublicKey().getAlgorithm();
+ default -> null;
+ };
+ if (algorithm == null) {
+ publishMessage(
+ getResponseTopic(topic),
+ new ErrorResponseMessage(ErrorResponseMessage.Error.UNAUTHORIZED),
+ MqttQoS.AT_MOST_ONCE);
+ return;
+ }
+
+ byte[] nonce = new byte[32];
+ challengeRandom.nextBytes(nonce);
+ String challenge =
+ X509ProvisioningChallengeResponseMessage.CHALLENGE_PREFIX
+ + topic
+ + "\n"
+ + Base64.getEncoder().encodeToString(nonce);
+ provisioningChallenges.put(
+ connection, new X509Challenge(topic.toString(), certificate, challenge, algorithm));
+ publishMessage(
+ getResponseTopic(topic),
+ new X509ProvisioningChallengeResponseMessage(challenge, algorithm),
+ MqttQoS.AT_MOST_ONCE);
+ }
+
+ protected boolean verifyX509Proof(
+ RemotingConnection connection, Topic topic, X509Certificate certificate, String signature) {
+ // Atomically consume the challenge even if the proof is invalid. Replays must never succeed.
+ X509Challenge challenge = provisioningChallenges.asMap().remove(connection);
+ if (challenge == null
+ || TextUtil.isNullOrEmpty(signature)
+ || !challenge.topic().equals(topic.toString())
+ || !challenge.certificate().equals(certificate)
+ || !ownsResponseTopic(connection, topic)) {
+ return false;
+ }
+ try {
+ Signature verifier = Signature.getInstance(challenge.algorithm());
+ verifier.initVerify(certificate.getPublicKey());
+ verifier.update(challenge.challenge().getBytes(StandardCharsets.UTF_8));
+ return verifier.verify(Base64.getDecoder().decode(signature));
+ } catch (GeneralSecurityException | IllegalArgumentException e) {
+ LOG.fine(
+ "Invalid X.509 provisioning proof: " + MQTTBrokerService.connectionToString(connection));
+ return false;
+ }
+ }
+
+ protected void clearConnectionState(RemotingConnection connection) {
+ // Mark first so a concurrent canSubscribe backs out of any claim made after the removes below
+ closedConnections.add(connection);
+ provisioningChallenges.invalidate(connection);
+ String responseTopic = connectionResponseTopics.remove(connection);
+
+ if (responseTopic != null) {
+ responseTopicOwners.remove(responseTopic, connection);
+ }
+ }
+
+ @Override
+ public void stop() throws Exception {
+ provisioningChallenges.invalidateAll();
+ super.stop();
+ }
+
protected X509ProvisioningConfig getMatchingX509ProvisioningConfig(
RemotingConnection connection, X509Certificate clientCertificate) {
return provisioningService.getProvisioningConfigs().stream()
diff --git a/manager/test/src/groovy/org/openremote/manager/mqtt/X509ProvisioningProofTest.groovy b/manager/test/src/groovy/org/openremote/manager/mqtt/X509ProvisioningProofTest.groovy
new file mode 100644
index 000000000..6240877a3
--- /dev/null
+++ b/manager/test/src/groovy/org/openremote/manager/mqtt/X509ProvisioningProofTest.groovy
@@ -0,0 +1,453 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * 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 <https://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+package org.openremote.manager.mqtt
+
+import com.google.common.base.Ticker
+import io.netty.handler.codec.mqtt.MqttQoS
+import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection
+import org.apache.activemq.artemis.spi.core.remoting.Connection
+import org.openremote.model.protocol.mqtt.Topic
+import org.openremote.model.provisioning.ProvisioningMessage
+import org.openremote.model.provisioning.X509ProvisioningChallengeRequestMessage
+import org.openremote.model.provisioning.X509ProvisioningChallengeResponseMessage
+import org.openremote.model.provisioning.X509ProvisioningMessage
+import org.openremote.model.util.ValueUtil
+import spock.lang.Specification
+
+import java.nio.charset.StandardCharsets
+import java.security.KeyPair
+import java.security.KeyPairGenerator
+import java.security.Signature
+import java.security.cert.X509Certificate
+import java.util.concurrent.Callable
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.Executors
+import java.util.concurrent.TimeUnit
+
+class X509ProvisioningProofTest extends Specification {
+
+ def ticker = new TestTicker()
+ def handler = new TestHandler(ticker)
+ def connection = Stub(RemotingConnection) {
+ getClientID() >> "device-client"
+ getTransportConnection() >> Stub(Connection) {
+ isOpen() >> true
+ }
+ }
+ def topic = Topic.parse("provisioning/device1/request")
+ def keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair()
+ def certificate = certificateFor(keyPair)
+
+ def setup() {
+ handler.isKeycloak = true
+ assert handler.canSubscribe(connection, null, Topic.parse("provisioning/device1/response"))
+ handler.onSubscribe(connection, Topic.parse("provisioning/device1/response"))
+ }
+
+ def "a valid #keyAlgorithm proof succeeds exactly once"() {
+ given:
+ def keys = KeyPairGenerator.getInstance(keyAlgorithm).generateKeyPair()
+ def cert = certificateFor(keys)
+ handler.issueX509Challenge(connection, topic, cert)
+ def challenge = handler.messages.last() as X509ProvisioningChallengeResponseMessage
+ def signature = sign(challenge, keys)
+
+ expect:
+ handler.verifyX509Proof(connection, topic, cert, signature)
+ !handler.verifyX509Proof(connection, topic, cert, signature)
+
+ where:
+ keyAlgorithm << ["RSA", "EC", "Ed25519", "Ed448"]
+ }
+
+ def "a public certificate without proof never authenticates"() {
+ given:
+ handler.issueX509Challenge(connection, topic, certificate)
+
+ expect:
+ !handler.verifyX509Proof(connection, topic, certificate, null)
+ handler.provisioningChallenges.size() == 0
+ }
+
+ def "a signature is bound to the transport connection even when the client ID is reused"() {
+ given:
+ def otherConnection = Stub(RemotingConnection) {
+ getClientID() >> "device-client"
+ }
+ handler.issueX509Challenge(connection, topic, certificate)
+ def signature = sign(handler.messages.last(), keyPair)
+
+ expect:
+ !handler.verifyX509Proof(otherConnection, topic, certificate, signature)
+ handler.verifyX509Proof(connection, topic, certificate, signature)
+ }
+
+ def "a signature cannot be used with another topic or certificate"() {
+ given:
+ handler.issueX509Challenge(connection, topic, certificate)
+ def signature = sign(handler.messages.last(), keyPair)
+ def otherCertificate = certificateFor(KeyPairGenerator.getInstance("RSA").generateKeyPair())
+
+ expect:
+ !handler.verifyX509Proof(connection, Topic.parse("provisioning/device2/request"), certificate, signature)
+
+ when:
+ handler.issueX509Challenge(connection, topic, certificate)
+ signature = sign(handler.messages.last(), keyPair)
+
+ then:
+ !handler.verifyX509Proof(connection, topic, otherCertificate, signature)
+ }
+
+ def "a wrong private key or malformed signature consumes the challenge"() {
+ given:
+ handler.issueX509Challenge(connection, topic, certificate)
+ def challenge = handler.messages.last()
+ def wrongKey = KeyPairGenerator.getInstance("RSA").generateKeyPair()
+ def signature = malformed ? "not base64!" : sign(challenge, wrongKey)
+
+ expect:
+ !handler.verifyX509Proof(connection, topic, certificate, signature)
+ !handler.verifyX509Proof(connection, topic, certificate, sign(challenge, keyPair))
+
+ where:
+ malformed << [true, false]
+ }
+
+ def "a superseded challenge cannot be replayed"() {
+ given:
+ handler.issueX509Challenge(connection, topic, certificate)
+ def oldChallenge = handler.messages.last()
+ handler.issueX509Challenge(connection, topic, certificate)
+ def newChallenge = handler.messages.last()
+
+ expect:
+ oldChallenge.challenge != newChallenge.challenge
+ !handler.verifyX509Proof(connection, topic, certificate, sign(oldChallenge, keyPair))
+ !handler.verifyX509Proof(connection, topic, certificate, sign(newChallenge, keyPair))
+ }
+
+ def "challenges expire at sixty seconds"() {
+ given:
+ handler.issueX509Challenge(connection, topic, certificate)
+ def signature = sign(handler.messages.last(), keyPair)
+
+ when:
+ ticker.nanos += TimeUnit.SECONDS.toNanos(60)
+
+ then:
+ !handler.verifyX509Proof(connection, topic, certificate, signature)
+ }
+
+ def "only the response topic owner can publish provisioning requests"() {
+ given:
+ def attacker = Stub(RemotingConnection)
+
+ expect: "the owning connection may publish its own request topic"
+ handler.canPublish(connection, null, topic)
+
+ and: "nobody else may, so an attacker cannot inject errors into the device's exchange"
+ !handler.canPublish(attacker, null, topic)
+ !handler.canPublish(connection, null, Topic.parse("provisioning/device2/request"))
+ handler.messages.isEmpty()
+ }
+
+ def "publishing is refused until the response topic has been claimed"() {
+ given:
+ def device2 = Stub(RemotingConnection) {
+ getTransportConnection() >> Stub(Connection) {
+ isOpen() >> true
+ }
+ }
+ def unsubscribed = Topic.parse("provisioning/device2/request")
+
+ expect:
+ !handler.canPublish(device2, null, unsubscribed)
+
+ when:
+ handler.canSubscribe(device2, null, Topic.parse("provisioning/device2/response"))
+
+ then:
+ handler.canPublish(device2, null, unsubscribed)
+
+ when:
+ handler.onUnsubscribe(device2, Topic.parse("provisioning/device2/response"))
+
+ then:
+ !handler.canPublish(device2, null, unsubscribed)
+ }
+
+ def "a connection can own only one response topic"() {
+ given:
+ def device1Response = Topic.parse("provisioning/device1/response")
+ def device2Response = Topic.parse("provisioning/device2/response")
+
+ expect: "re-authorizing the topic it already owns is allowed"
+ handler.canSubscribe(connection, null, device1Response)
+
+ and: "claiming a second device's topic is refused and leaves that topic free"
+ !handler.canSubscribe(connection, null, device2Response)
+ !handler.responseTopicOwners.containsKey(device2Response.toString())
+ handler.connectionResponseTopics[connection] == device1Response.toString()
+
+ when: "the connection releases its topic"
+ handler.onUnsubscribe(connection, device1Response)
+
+ then: "it may claim another"
+ handler.canSubscribe(connection, null, device2Response)
+ handler.connectionResponseTopics[connection] == device2Response.toString()
+ !handler.responseTopicOwners.containsKey(device1Response.toString())
+ }
+
+ def "losing a topic race does not use up the connection's one claim"() {
+ given:
+ def other = Stub(RemotingConnection) {
+ getTransportConnection() >> Stub(Connection) {
+ isOpen() >> true
+ }
+ }
+
+ expect: "another connection cannot take the owned topic"
+ !handler.canSubscribe(other, null, Topic.parse("provisioning/device1/response"))
+
+ and: "but can still claim a free one"
+ handler.canSubscribe(other, null, Topic.parse("provisioning/device2/response"))
+ }
+
+ def "only the response subscriber can obtain a challenge"() {
+ given:
+ def attacker = Stub(RemotingConnection)
+
+ when:
+ handler.issueX509Challenge(attacker, topic, certificate)
+
+ then: "no challenge is issued and nothing is published to the owner's response topic"
+ handler.messages.isEmpty()
+ handler.provisioningChallenges.size() == 0
+ }
+
+ def "a message processed after its connection lost the response topic is dropped silently"() {
+ given: "the topic changes hands after the message was authorized but before it is processed"
+ def newOwner = openConnection()
+ handler.onUnsubscribe(connection, Topic.parse("provisioning/device1/response"))
+ assert handler.canSubscribe(newOwner, null, Topic.parse("provisioning/device1/response"))
+
+ when:
+ handler.processX509ProvisioningMessage(connection, topic, cert, signature, challengeRequest)
+
+ then: "nothing is published to the new owner's response topic"
+ handler.messages.isEmpty()
+ handler.provisioningChallenges.size() == 0
+
+ where:
+ challengeRequest | cert | signature
+ true | "certificate" | null
+ false | "certificate" | "signature"
+ false | null | null
+ }
+
+ def "a proof fails after the response subscription changes ownership"() {
+ given:
+ handler.issueX509Challenge(connection, topic, certificate)
+ def signature = sign(handler.messages.last(), keyPair)
+ handler.onUnsubscribe(connection, Topic.parse("provisioning/device1/response"))
+ def otherConnection = Stub(RemotingConnection)
+ assert handler.canSubscribe(otherConnection, null, Topic.parse("provisioning/device1/response"))
+ handler.onSubscribe(otherConnection, Topic.parse("provisioning/device1/response"))
+
+ expect:
+ !handler.verifyX509Proof(connection, topic, certificate, signature)
+ }
+
+ def "disconnect and connection loss clear challenges and response topic claims"() {
+ given:
+ handler.issueX509Challenge(connection, topic, certificate)
+ def signature = sign(handler.messages.last(), keyPair)
+
+ when:
+ if (abrupt) {
+ handler.onConnectionLost(connection)
+ } else {
+ handler.onDisconnect(connection)
+ }
+
+ then: "the unfinished challenge is invalidated"
+ !handler.verifyX509Proof(connection, topic, certificate, signature)
+
+ and: "the connection's response topic claim is cleared"
+ handler.responseTopicOwners.isEmpty()
+ handler.connectionResponseTopics.isEmpty()
+
+ where:
+ abrupt << [true, false]
+ }
+
+ def "a subscribe authorized after disconnect cleanup leaves nothing behind"() {
+ given: "a connection whose cleanup has run while its transport still reports open, as Artemis calls the disconnect callbacks before closing it"
+ def closing = openConnection()
+ def realDevice = openConnection()
+ handler.onDisconnect(closing)
+
+ expect: "the late subscribe is refused and no claim survives"
+ !handler.canSubscribe(closing, null, Topic.parse("provisioning/device2/response"))
+ !handler.responseTopicOwners.containsKey("provisioning/device2/response")
+ !handler.connectionResponseTopics.containsKey(closing)
+
+ and: "the topic stays free for the real device"
+ handler.canSubscribe(realDevice, null, Topic.parse("provisioning/device2/response"))
+ }
+
+ def "concurrent subscribe and disconnect never leak a claim"() {
+ given:
+ def executor = Executors.newFixedThreadPool(2)
+ def responseTopic = Topic.parse("provisioning/device2/response")
+
+ when: "a subscribe and the disconnect cleanup of the same connection race many times"
+ def leaks = (1..500).count {
+ def racing = openConnection()
+ def start = new CountDownLatch(1)
+ executor.invokeAll([
+ { start.await(); handler.canSubscribe(racing, null, responseTopic) } as Callable,
+ { start.countDown(); handler.onDisconnect(racing) } as Callable
+ ])
+ def leaked = handler.connectionResponseTopics.containsKey(racing) ||
+ handler.responseTopicOwners[responseTopic.toString()].is(racing)
+ handler.responseTopicOwners.remove(responseTopic.toString())
+ leaked
+ }
+
+ then:
+ leaks == 0
+
+ cleanup:
+ executor.shutdownNow()
+ }
+
+ def "concurrent submissions cannot reuse a challenge"() {
+ given:
+ handler.issueX509Challenge(connection, topic, certificate)
+ def signature = sign(handler.messages.last(), keyPair)
+ def executor = Executors.newFixedThreadPool(2)
+
+ when:
+ def results = executor.invokeAll((1..2).collect {
+ { handler.verifyX509Proof(connection, topic, certificate, signature) } as Callable<Boolean>
+ }).collect { it.get() }
+
+ then:
+ results.count(true) == 1
+ results.count(false) == 1
+
+ cleanup:
+ executor.shutdownNow()
+ }
+
+ def "concurrent subscriptions cannot share the response topic"() {
+ given:
+ handler.isKeycloak = true
+ def transport = Stub(Connection) {
+ isOpen() >> true
+ }
+ def connections = (1..2).collect {
+ Stub(RemotingConnection) {
+ getTransportConnection() >> transport
+ }
+ }
+ def responseTopic = Topic.parse("provisioning/device2/response")
+ def executor = Executors.newFixedThreadPool(2)
+
+ when:
+ def results = executor.invokeAll(connections.collect { candidate ->
+ { handler.canSubscribe(candidate, null, responseTopic) } as Callable<Boolean>
+ }).collect { it.get() }
+
+ then:
+ results.count(true) == 1
+ results.count(false) == 1
+ handler.responseTopicOwners[responseTopic.toString()].is(connections[results.indexOf(true)])
+
+ and: "only the winner may publish the matching request topic"
+ handler.canPublish(connections[results.indexOf(true)], null, Topic.parse("provisioning/device2/request"))
+ !handler.canPublish(connections[results.indexOf(false)], null, Topic.parse("provisioning/device2/request"))
+
+ cleanup:
+ executor.shutdownNow()
+ }
+
+ def "provisioning messages survive JSON serialization with their wire types"() {
+ given:
+ def messages = [
+ new X509ProvisioningChallengeRequestMessage("public certificate"),
+ new X509ProvisioningChallengeResponseMessage("challenge", "SHA256withRSA"),
+ new X509ProvisioningMessage("public certificate", "signature"),
+ new X509ProvisioningMessage("public certificate")
+ ]
+
+ expect:
+ messages.every { message ->
+ def json = ValueUtil.asJSON(message).orElseThrow()
+ def decoded = ValueUtil.parse(json, ProvisioningMessage.class).orElseThrow()
+ decoded.class == message.class && ValueUtil.asJSON(decoded).orElseThrow() == json
+ }
+ }
+
+ RemotingConnection openConnection() {
+ Stub(RemotingConnection) {
+ getTransportConnection() >> Stub(Connection) {
+ isOpen() >> true
+ }
+ }
+ }
+
+ X509Certificate certificateFor(KeyPair keys) {
+ Stub(X509Certificate) {
+ getPublicKey() >> keys.public
+ getEncoded() >> keys.public.encoded
+ }
+ }
+
+ static String sign(X509ProvisioningChallengeResponseMessage challenge, KeyPair keys) {
+ def signer = Signature.getInstance(challenge.algorithm)
+ signer.initSign(keys.private)
+ signer.update(challenge.challenge.getBytes(StandardCharsets.UTF_8))
+ Base64.encoder.encodeToString(signer.sign())
+ }
+
+ static class TestTicker extends Ticker {
+ long nanos
+
+ @Override
+ long read() {
+ nanos
+ }
+ }
+
+ static class TestHandler extends UserAssetProvisioningMQTTHandler {
+ List<ProvisioningMessage> messages = []
+
+ TestHandler(Ticker ticker) {
+ super(ticker)
+ }
+
+ @Override
+ void publishMessage(String topic, Object data, MqttQoS qos) {
+ messages.add(data as ProvisioningMessage)
+ }
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/provisioning/ProvisioningMessage.java b/model/src/main/java/org/openremote/model/provisioning/ProvisioningMessage.java
index 3a86c2804..8d15f3659 100644
--- a/model/src/main/java/org/openremote/model/provisioning/ProvisioningMessage.java
+++ b/model/src/main/java/org/openremote/model/provisioning/ProvisioningMessage.java
@@ -25,6 +25,12 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonSubTypes({
@JsonSubTypes.Type(name = "error", value = ErrorResponseMessage.class),
@JsonSubTypes.Type(name = "success", value = SuccessResponseMessage.class),
+ @JsonSubTypes.Type(
+ name = "x509-challenge-request",
+ value = X509ProvisioningChallengeRequestMessage.class),
+ @JsonSubTypes.Type(
+ name = "x509-challenge",
+ value = X509ProvisioningChallengeResponseMessage.class),
@JsonSubTypes.Type(name = "x509", value = X509ProvisioningMessage.class)
})
public abstract class ProvisioningMessage {}
diff --git a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningChallengeRequestMessage.java b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningChallengeRequestMessage.java
new file mode 100644
index 000000000..e04e76ea6
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningChallengeRequestMessage.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * 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 <https://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+package org.openremote.model.provisioning;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * Requests a challenge on the connection that owns the device's provisioning response topic; the
+ * answer is an {@link X509ProvisioningChallengeResponseMessage}. This is a sibling of {@link
+ * X509ProvisioningMessage} rather than a subclass so that it carries no unused signature field and
+ * so that the two steps of the exchange stay distinguishable.
+ */
+public class X509ProvisioningChallengeRequestMessage extends ProvisioningMessage {
+
+ protected String cert;
+
+ @JsonCreator
+ public X509ProvisioningChallengeRequestMessage(@JsonProperty("cert") String cert) {
+ this.cert = cert;
+ }
+
+ public String getCert() {
+ return cert;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningChallengeResponseMessage.java b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningChallengeResponseMessage.java
new file mode 100644
index 000000000..084bbee98
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningChallengeResponseMessage.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * 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 <https://www.gnu.org/licenses/>.
+ *
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+package org.openremote.model.provisioning;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * A one-time challenge, valid for 60 seconds on the requesting MQTT connection only. Sign the exact
+ * UTF-8 bytes of {@code challenge} with the certificate's private key using {@code algorithm}, then
+ * send the Base64-encoded signature in an {@link X509ProvisioningMessage} on the same connection.
+ *
+ * <p>Clients must verify that {@code challenge} starts with {@link #CHALLENGE_PREFIX} and that the
+ * topic line that follows is their own request topic before signing anything; otherwise a device
+ * acts as a signing oracle for arbitrary data sent by whatever is on the other end of the
+ * connection, which matters particularly when the same key is also used for TLS client
+ * authentication.
+ */
+public class X509ProvisioningChallengeResponseMessage extends ProvisioningMessage {
+
+ /** Domain separator that every challenge issued by the manager starts with. */
+ public static final String CHALLENGE_PREFIX = "OpenRemote MQTT X509 provisioning v1\n";
+
+ protected String challenge;
+ protected String algorithm;
+
+ @JsonCreator
+ public X509ProvisioningChallengeResponseMessage(
+ @JsonProperty("challenge") String challenge, @JsonProperty("algorithm") String algorithm) {
+ this.challenge = challenge;
+ this.algorithm = algorithm;
+ }
+
+ public String getChallenge() {
+ return challenge;
+ }
+
+ public String getAlgorithm() {
+ return algorithm;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningMessage.java b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningMessage.java
index 88e0b3a98..10b44c795 100644
--- a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningMessage.java
+++ b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningMessage.java
@@ -19,16 +19,30 @@
package org.openremote.model.provisioning;
import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+/** Completes an X.509 provisioning challenge using proof of possession of the private key. */
public class X509ProvisioningMessage extends ProvisioningMessage {
protected String cert;
+ protected String signature;
- @JsonCreator
public X509ProvisioningMessage(String cert) {
+ this(cert, null);
+ }
+
+ @JsonCreator
+ public X509ProvisioningMessage(
+ @JsonProperty("cert") String cert, @JsonProperty("signature") String signature) {
this.cert = cert;
+ this.signature = signature;
}
public String getCert() {
return cert;
}
+
+ /** Base64-encoded signature over the UTF-8 bytes of the server's challenge. */
+ public String getSignature() {
+ return signature;
+ }
}
diff --git a/test/load1/README.md b/test/load1/README.md
index e2c1bf412..1a4046805 100644
--- a/test/load1/README.md
+++ b/test/load1/README.md
@@ -94,6 +94,21 @@ Simulates auto provisioning devices connecting to the Manager via MQTT as follow
#### Device X.509 certificates (for auto provisioning)
+The `deployment3/auto-provisioning*.jmx` plans send only a public certificate and are rejected
+with `UNAUTHORIZED` by the proof-of-possession provisioning protocol; they need updating before
+they can be used against a manager that includes that change, which is tracked in
+[#3542](https://github.com/openremote/core/issues/3542). A plan has to subscribe to
+`provisioning/${id}/response` first (only the owner of that topic may publish requests), publish
+an `x509-challenge-request`, sign the received challenge and publish the signature back. All
+devices generated by `device_generator.sh` share the single private key it writes to
+`tmp/device.pem`, so a JSR223 sampler can load that one key and sign for every device. That key
+is deleted on the next run and the one behind the committed `deployment3/devices.csv` is not in
+the repository, so the CSV has to be regenerated with a key that is kept alongside it. The
+exchange is documented in the
+[auto provisioning docs](https://docs.openremote.io/docs/user-guide/gateways-and-devices/auto-provisioning)
+and in the `UserAssetProvisioningMQTTHandler` javadoc, with a working client example in
+[`UserAndAssetProvisioningTest`](../src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy).
+
The test requires device client X.509 certificates to be available at './devices.csv'; the file
contains 10,000 pre-generated device certificates but if more devices are required then use the `device_generator.sh COUNT`
script to generate a new file the COUNT value is the number of devices to generate certificates for (default: 100).
diff --git a/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy b/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy
index 7ea38cbaa..854fbfd23 100644
--- a/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy
@@ -20,9 +20,14 @@ package org.openremote.test.provisioning
import com.hivemq.client.internal.mqtt.mqtt3.Mqtt3AsyncClientView
import com.hivemq.client.internal.mqtt.mqtt3.Mqtt3ClientConfigView
+import com.hivemq.client.mqtt.datatypes.MqttQos
import com.hivemq.client.mqtt.MqttClientConfig
import com.hivemq.client.mqtt.MqttClientConnectionConfig
import io.netty.channel.socket.SocketChannel
+import org.bouncycastle.openssl.PEMKeyPair
+import org.bouncycastle.openssl.PEMParser
+import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter
+import org.openremote.model.protocol.mqtt.Topic
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection
import org.keycloak.admin.client.resource.RealmResource
import org.keycloak.representations.idm.RoleRepresentation
@@ -59,7 +64,10 @@ import org.openremote.setup.integration.ManagerTestSetup
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
+import java.nio.charset.StandardCharsets
+import java.security.Signature
import java.util.concurrent.CopyOnWriteArrayList
+import java.util.concurrent.TimeUnit
import java.util.function.Consumer
import static org.openremote.manager.mqtt.MQTTBrokerService.getConnectionIDString
@@ -100,7 +108,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
// asynchronously and a response published before then is lost, so requests must await the broker side
def responseSubscribed = { String clientId, String responseTopic ->
def brokerConnection = mqttBrokerService.getConnectionFromClientID(clientId)
- brokerConnection != null && userAssetProvisioningMQTTHandler.responseSubscribedConnections.get(responseTopic) === brokerConnection
+ brokerConnection != null && userAssetProvisioningMQTTHandler.responseTopicOwners.get(responseTopic) === brokerConnection
}
and: "a realm is created with some custom realm roles"
@@ -193,11 +201,19 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
when: "the client subscribes to the provisioning endpoints"
List<ProvisioningMessage> device1Responses = new CopyOnWriteArrayList<>()
- Consumer<MQTTMessage<String>> device1MessageConsumer = { MQTTMessage<String> msg ->
- device1Responses.add(ValueUtil.parse(msg.payload, ProvisioningMessage.class).orElse(null))
- }
+ List<X509ProvisioningMessage> device1Proofs = new CopyOnWriteArrayList<>()
def device1RequestTopic = "$PROVISIONING_TOKEN/$device1UniqueId/$REQUEST_TOKEN".toString()
def device1ResponseTopic = "$PROVISIONING_TOKEN/$device1UniqueId/$RESPONSE_TOKEN".toString()
+ Consumer<MQTTMessage<String>> device1MessageConsumer = { MQTTMessage<String> msg ->
+ def response = ValueUtil.parse(msg.payload, ProvisioningMessage.class).orElse(null)
+ if (response instanceof X509ProvisioningChallengeResponseMessage) {
+ def proof = signChallenge(response, "device1")
+ device1Proofs.add(proof)
+ device1Client.sendMessage(new MQTTMessage<String>(device1RequestTopic, ValueUtil.asJSON(proof).orElseThrow()))
+ } else {
+ device1Responses.add(response)
+ }
+ }
device1Client.addMessageConsumer(device1ResponseTopic, device1MessageConsumer)
then: "the subscriptions should succeed"
@@ -235,12 +251,28 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
assert responseSubscribed(mqttDevice1ClientId, device1ResponseTopic)
}
+ when: "a public certificate alone is submitted before the device has been provisioned"
+ device1Client.sendMessage(new MQTTMessage<String>(device1RequestTopic, ValueUtil.asJSON(
+ new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
+ ).orElseThrow()))
+
+ then: "enrollment is rejected without creating a service user or asset"
+ conditions.eventually {
+ assert device1Responses.size() == 1
+ assert device1Responses[0] instanceof ErrorResponseMessage
+ assert device1Responses[0].error == ErrorResponseMessage.Error.UNAUTHORIZED
+ }
+ assert identityService.identityProvider.getUserByUsername(managerTestSetup.realmBuildingName,
+ User.SERVICE_ACCOUNT_PREFIX + PROVISIONING_USER_PREFIX + device1UniqueId) == null
+ assert assetStorageService.find(UniqueIdentifierGenerator.generateId(provisioningConfig.realm + device1UniqueId)) == null
+
when: "the client publishes a valid x509 certificate that has been signed by the CA stored in the provisioning config"
+ device1Responses.clear()
subscribeFailures.clear()
def existingConnection = mqttBrokerService.getConnectionFromClientID(mqttDevice1ClientId)
device1Client.sendMessage(
new MQTTMessage<String>(device1RequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
).orElse(null))
)
@@ -265,6 +297,66 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
assert mqttBrokerService.getConnectionFromClientID(mqttDevice1ClientId) == existingConnection
}
+ when: "an unrelated anonymous client that does not own the response topic publishes requests"
+ def device1ServiceUser = identityService.identityProvider.getUserByUsername(
+ managerTestSetup.realmBuildingName,
+ User.SERVICE_ACCOUNT_PREFIX + PROVISIONING_USER_PREFIX + device1UniqueId)
+ def attackerConnection = mqttBrokerService.getConnectionFromClientID(mqttDevice1SnoopClientId)
+ def attackerSubject = attackerConnection.subject
+ def device1Pem = getClass().getResource("/org/openremote/test/provisioning/device1.pem").text
+ device1Responses.clear()
+ def proofCount = device1Proofs.size()
+ [
+ new X509ProvisioningMessage(device1Pem),
+ new X509ProvisioningChallengeRequestMessage(device1Pem),
+ device1Proofs.last()
+ ].each { message ->
+ device1SnoopClient.sendMessage(new MQTTMessage<String>(device1RequestTopic,
+ ValueUtil.asJSON(message).orElseThrow()))
+ }
+
+ then: "the broker refuses the publishes so the device's own exchange is never disturbed"
+ // This asserts an absence, so it is a quiet period rather than a wait for something to happen:
+ // the initial delay gives any wrongly processed publish time to produce a response, and the
+ // block then passes on its first poll if nothing arrived.
+ new PollingConditions(initialDelay: 2, timeout: 10, delay: 0.5).eventually {
+ assert device1Responses.isEmpty()
+ assert device1Proofs.size() == proofCount
+ }
+
+ and: "the attacker remains anonymous"
+ assert attackerConnection.subject.is(attackerSubject)
+ assert !mqttBrokerService.getUserConnections(device1ServiceUser.id).contains(attackerConnection)
+ assert !userAssetProvisioningMQTTHandler.canPublish(attackerConnection, null, Topic.parse(device1RequestTopic))
+ assert !defaultMQTTHandler.checkCanPublish(attackerConnection,
+ defaultMQTTHandler.getAuthContextFromConnection(attackerConnection).orElse(null), Topic.parse(
+ "$provisioningConfig.realm/$mqttDevice1SnoopClientId/$DefaultMQTTHandler.ATTRIBUTE_VALUE_WRITE_TOPIC/customAttribute/${weatherAsset.id}"))
+
+ when: "the anonymous attacker attempts the original restricted attribute write"
+ def originalAttributeValue = assetStorageService.find(weatherAsset.id).getAttribute("customAttribute")
+ .flatMap { it.getValue() }.orElse(null)
+ conditions.eventually {
+ assert device1SnoopClient.getConnectionStatus() == ConnectionStatus.CONNECTED
+ }
+ device1SnoopClient.client.publishWith()
+ .topic("$provisioningConfig.realm/$mqttDevice1SnoopClientId/$DefaultMQTTHandler.ATTRIBUTE_VALUE_WRITE_TOPIC/customAttribute/${weatherAsset.id}")
+ .payload("31337".getBytes(StandardCharsets.UTF_8))
+ .qos(MqttQos.AT_LEAST_ONCE).send()
+ .orTimeout(5, TimeUnit.SECONDS)
+ .handle { publish, error -> error }.get(10, TimeUnit.SECONDS)
+
+ then: "the protected attribute remains unchanged"
+ assert assetStorageService.find(weatherAsset.id).getAttribute("customAttribute")
+ .flatMap { it.getValue() }.orElse(null) == originalAttributeValue
+
+ when: "the attacker connection is removed"
+ device1SnoopClient.disconnect()
+
+ then: "the attacker connection is removed from the broker"
+ conditions.eventually {
+ assert mqttBrokerService.getConnectionFromClientID(mqttDevice1SnoopClientId) == null
+ }
+
when: "the client gets abruptly disconnected"
device1Responses.clear()
existingConnection = mqttBrokerService.getConnectionFromClientID(mqttDevice1ClientId)
@@ -285,10 +377,24 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
assert mqttBrokerService.getConnectionFromClientID(mqttDevice1ClientId) != null
}
+ when: "the reconnected client replays the proof from its previous connection"
+ device1Client.sendMessage(new MQTTMessage<String>(device1RequestTopic,
+ ValueUtil.asJSON(device1Proofs.last()).orElseThrow()))
+
+ then: "reusing the MQTT client ID does not make an old proof valid"
+ conditions.eventually {
+ assert device1Responses.size() == 1
+ assert device1Responses[0] instanceof ErrorResponseMessage
+ assert device1Responses[0].error == ErrorResponseMessage.Error.UNAUTHORIZED
+ }
+ assert !mqttBrokerService.getUserConnections(device1ServiceUser.id)
+ .contains(mqttBrokerService.getConnectionFromClientID(mqttDevice1ClientId))
+
when: "the client publishes a valid x509 certificate that has been signed by the CA stored in the provisioning config"
+ device1Responses.clear()
device1Client.sendMessage(
new MQTTMessage<String>(device1RequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
).orElse(null))
)
@@ -420,7 +526,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
conditions.eventually {
assert !defaultMQTTHandler.sessionSubscriptionConsumers.containsKey(getConnectionIDString(connection))
assert device1Client.getConnectionStatus() == ConnectionStatus.DISCONNECTED
- assert userAssetProvisioningMQTTHandler.responseSubscribedConnections.isEmpty()
+ assert userAssetProvisioningMQTTHandler.responseTopicOwners.isEmpty()
}
and: "the connected attribute of the provisioned asset should show as not connected"
@@ -457,7 +563,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
device1Responses.clear()
device1Client.sendMessage(
new MQTTMessage<String>(device1RequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
).orElse(null))
)
@@ -514,7 +620,13 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
when: "the client subscribes to the provisioning endpoints"
List<ProvisioningMessage> deviceNResponses = new CopyOnWriteArrayList<>()
Consumer<MQTTMessage<String>> deviceNMessageConsumer = { MQTTMessage<String> msg ->
- deviceNResponses.add(ValueUtil.parse(msg.payload, ProvisioningMessage.class).orElse(null))
+ def response = ValueUtil.parse(msg.payload, ProvisioningMessage.class).orElse(null)
+ if (response instanceof X509ProvisioningChallengeResponseMessage) {
+ def proof = signChallenge(response, "device3_caexpired")
+ deviceNClient.sendMessage(new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(proof).orElseThrow()))
+ } else {
+ deviceNResponses.add(response)
+ }
}
deviceNClient.addMessageConsumer(deviceNResponseTopic, deviceNMessageConsumer)
@@ -529,7 +641,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
when: "the client publishes an expired but valid x509 certificate that has been signed by the CA stored in the provisioning config"
deviceNClient.sendMessage(
new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device2_expired.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device2_expired.pem").text)
).orElse(null))
)
@@ -540,6 +652,19 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
assert ((ErrorResponseMessage)deviceNResponses.get(0)).error == ErrorResponseMessage.Error.UNAUTHORIZED
}
+ when: "a valid certificate is submitted on a different device's topic"
+ deviceNResponses.clear()
+ deviceNClient.sendMessage(new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
+ ).orElseThrow()))
+
+ then: "the certificate common name must still match the topic"
+ conditions.eventually {
+ assert deviceNResponses.size() == 1
+ assert deviceNResponses[0] instanceof ErrorResponseMessage
+ assert deviceNResponses[0].error == ErrorResponseMessage.Error.UNIQUE_ID_MISMATCH
+ }
+
when: "the client disconnects"
deviceNClient.removeAllMessageConsumers()
deviceNClient.disconnect()
@@ -579,7 +704,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
when: "the client publishes a forged x509 certificate that has been signed by a forged CA"
deviceNClient.sendMessage(
new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device4_forged.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device4_forged.pem").text)
).orElse(null))
)
@@ -629,7 +754,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
when: "the client publishes a valid x509 certificate that has been signed by the CA stored in the provisioning config but against an expired certificate"
deviceNClient.sendMessage(
new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device3_caexpired.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device3_caexpired.pem").text)
).orElse(null))
)
@@ -680,7 +805,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
device1Responses.clear()
device1Client.sendMessage(
new MQTTMessage<String>(device1RequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
).orElse(null))
)
@@ -717,7 +842,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
when: "the client publishes a valid x509 certificate that has been signed by the CA stored in the provisioning config but against an expired certificate"
deviceNClient.sendMessage(
new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device3_caexpired.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device3_caexpired.pem").text)
).orElse(null))
)
@@ -749,7 +874,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
}
device1Client.sendMessage(
new MQTTMessage<String>(device1RequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
).orElse(null))
)
@@ -787,7 +912,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
device1Responses.clear()
device1Client.sendMessage(
new MQTTMessage<String>(device1RequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
).orElse(null))
)
@@ -824,7 +949,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
when: "the client publishes a valid x509 certificate that has been signed by the CA stored in the provisioning config but against an expired certificate"
deviceNClient.sendMessage(
new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device3_caexpired.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device3_caexpired.pem").text)
).orElse(null))
)
@@ -845,7 +970,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
device1Responses.clear()
device1Client.sendMessage(
new MQTTMessage<String>(device1RequestTopic, ValueUtil.asJSON(
- new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
+ new X509ProvisioningChallengeRequestMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
).orElse(null))
)
@@ -876,4 +1001,32 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
clientEventService.removeSubscription {internalConsumer}
}
}
+
+ /**
+ * The test certificates don't all have their own key; device3_caexpired was issued for the
+ * key of device2.
+ */
+ static final Map<String, String> CERTIFICATE_KEYS = [
+ "device1": "device1",
+ "device2_expired": "device2",
+ "device3_caexpired": "device2",
+ "device4_forged": "device4"
+ ]
+
+ static X509ProvisioningMessage signChallenge(X509ProvisioningChallengeResponseMessage challenge,
+ String certificateName) {
+ def keyName = CERTIFICATE_KEYS[certificateName]
+ assert keyName != null
+ def privateKey
+ UserAndAssetProvisioningTest.getResource("/org/openremote/test/provisioning/${keyName}.key").withReader { reader ->
+ def keyPair = new PEMParser(reader).readObject() as PEMKeyPair
+ privateKey = new JcaPEMKeyConverter().getKeyPair(keyPair).private
+ }
+ def signer = Signature.getInstance(challenge.algorithm)
+ signer.initSign(privateKey)
+ signer.update(challenge.challenge.getBytes(StandardCharsets.UTF_8))
+ return new X509ProvisioningMessage(
+ UserAndAssetProvisioningTest.getResource("/org/openremote/test/provisioning/${certificateName}.pem").text,
+ Base64.encoder.encodeToString(signer.sign()))
+ }
}