feat(iot): enforce custom authorizer decisions on MQTT connections (#4835)

* test(iot): cover custom authorizer invocation and enforcement against AWS

* feat(iot): enforce custom authorizer decisions on MQTT connections

Serve TestInvokeAuthorizer and invoke an authorizer's function on an MQTT
CONNECT that names it, on the plaintext listener and the /mqtt WebSocket
bridge. The event, the request and answer checks, signed-token
verification and the refusal per MQTT version follow what was measured
against AWS IoT Core. The bridge hands the upgrade's headers, query and
server name to the broker keyed by its connection's local address.

Closes #4823

* fix(iot): evaluate WebSocket custom authorizer policies against the client's address

* docs(iot): note that a non-UTF-8 MQTT password reaches the authorizer altered

* test(iot): cover custom authorizer CONNECTs on the plain MQTT listener

* fix(iot): refuse TestInvokeAuthorizer tokens and signatures outside their length bounds

* fix(iot): refuse authorizer JSON with trailing content

TestInvokeAuthorizer, CreateAuthorizer and UpdateAuthorizer bodies, a custom authorizer's answer and each policy document it returns are now read with FAIL_ON_TRAILING_TOKENS, as the shared JSON controllers do, so a valid prefix followed by junk is refused instead of half-read.

* fix(iot): keep address literals out of the WebSocket server name

Over WSS without SNI the bridge fell back to the Host header unfiltered,
so a client dialing an IP got that IP as tls.serverName in the authorizer
event and as iot:DomainName in policy evaluation. Apply the same address
literal filter SNI already uses. Also name the context validation ceiling
in TestInvokeAuthorizer's ponytail note.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-06 10:44:28 -04:00
1 parent e9f2463103
commit a33eea05cd
17 files changed
+2862 -50

No files matched your search

@@ -1,8 +1,10 @@
package io.github.hectorvent.floci.services.iot;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
@@ -26,7 +28,8 @@ import jakarta.ws.rs.core.Response;
/**
* REST-JSON routes for AWS IoT custom authorizers: CreateAuthorizer, DescribeAuthorizer,
* UpdateAuthorizer, DeleteAuthorizer, ListAuthorizers, SetDefaultAuthorizer,
* DescribeDefaultAuthorizer and ClearDefaultAuthorizer, on the paths and shapes the AWS SDKs use.
* DescribeDefaultAuthorizer, ClearDefaultAuthorizer and TestInvokeAuthorizer, on the paths and
* shapes the AWS SDKs use.
*/
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@@ -34,15 +37,19 @@ import jakarta.ws.rs.core.Response;
public class IotAuthorizerController {
private final IotAuthorizerService authorizerService;
private final IotCustomAuthorizer customAuthorizer;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final ObjectReader strictReader;
@Inject
public IotAuthorizerController(IotAuthorizerService authorizerService, RegionResolver regionResolver,
ObjectMapper objectMapper) {
public IotAuthorizerController(IotAuthorizerService authorizerService, IotCustomAuthorizer customAuthorizer,
RegionResolver regionResolver, ObjectMapper objectMapper) {
this.authorizerService = authorizerService;
this.customAuthorizer = customAuthorizer;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.strictReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
}
@POST
@@ -75,6 +82,14 @@ public class IotAuthorizerController {
return Response.ok(objectMapper.createObjectNode()).build();
}
@POST
@Path("/authorizer/{authorizerName}/test")
public Response testInvokeAuthorizer(@Context HttpHeaders headers, @PathParam("authorizerName") String authorizerName,
String body) {
return Response.ok(customAuthorizer.testInvoke(authorizerName, readJson(body), regionResolver.resolveRegion(headers)))
.build();
}
@GET
@Path("/authorizers")
public Response listAuthorizers(@Context HttpHeaders headers,
@@ -138,7 +153,7 @@ public class IotAuthorizerController {
private JsonNode readJson(String body) {
try {
return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
return strictReader.readTree(body == null || body.isBlank() ? "{}" : body);
} catch (JsonProcessingException e) {
throw new AwsException("InvalidRequestException", e.getMessage(), 400);
}
@@ -31,8 +31,8 @@ import java.util.stream.Collectors;
/**
* AWS IoT Core custom authorizers: the records CreateAuthorizer and its peers manage, and the
* account's default authorizer. The function ARN is checked for ARN syntax only, as on AWS; nothing
* here invokes the function or gates a connection.
* account's default authorizer. The function ARN is checked for ARN syntax only, as on AWS;
* {@link IotCustomAuthorizer} invokes the function.
*/
@ApplicationScoped
public class IotAuthorizerService {
@@ -333,8 +333,7 @@ public class IotAuthorizerService {
}
RSAPublicKey key;
try {
byte[] der = Base64.getDecoder().decode(String.join("", rest.subList(0, end)));
key = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(der));
key = rsaPublicKey(pem);
} catch (GeneralSecurityException | IllegalArgumentException e) {
throw invalid("Authorizer " + name + " public key for key name " + keyName + " not a valid RSA key");
}
@@ -345,6 +344,14 @@ public class IotAuthorizerService {
}
}
/** The key of a PEM whose header and end lines {@link #requireRsa2048} has checked. */
static RSAPublicKey rsaPublicKey(String pem) throws GeneralSecurityException {
List<String> lines = pem.lines().toList();
List<String> body = lines.subList(lines.indexOf("-----BEGIN PUBLIC KEY-----") + 1, lines.size());
byte[] der = Base64.getDecoder().decode(String.join("", body.subList(0, body.indexOf("-----END PUBLIC KEY-----"))));
return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(der));
}
private static void requireFunctionArn(String name, String functionArn) {
if (AwsArnUtils.resourceIfArnFor(functionArn, "lambda").filter(r -> r.startsWith("function:")).isEmpty()) {
throw invalid("Lambda function arn for authorizer " + name + " is not in proper ARN syntax");
@@ -380,7 +387,7 @@ public class IotAuthorizerService {
Map.of("resourceId", authorizer.getAuthorizerName(), "resourceArn", authorizer.getAuthorizerArn()));
}
private static AwsException constraint(String field, String constraint) {
static AwsException constraint(String field, String constraint) {
return constraints(field, List.of(constraint));
}
@@ -391,7 +398,7 @@ public class IotAuthorizerService {
.collect(Collectors.joining("; ")));
}
private static AwsException invalid(String message) {
static AwsException invalid(String message) {
return new AwsException("InvalidRequestException", message, 400);
}
@@ -0,0 +1,330 @@
package io.github.hectorvent.floci.services.iot;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.MissingNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.iot.model.IotAuthorizer;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Signature;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.regex.Pattern;
/**
* AWS IoT custom authentication: the event AWS IoT sends an authorizer's function, the invocation,
* and the checks AWS makes on the function's answer, in AWS's order and wording. TestInvokeAuthorizer
* and the MQTT CONNECT on the broker's plaintext listener, which the WebSocket bridge lands on, share
* it.
*/
@ApplicationScoped
public class IotCustomAuthorizer {
private static final Logger LOG = Logger.getLogger(IotCustomAuthorizer.class);
static final String NAME_PARAM = "x-amz-customauthorizer-name";
static final String SIGNATURE_PARAM = "x-amz-customauthorizer-signature";
private static final Pattern BASE64 = Pattern.compile("[A-Za-z0-9+/]+={0,2}");
private static final Pattern PRINCIPAL_ID = Pattern.compile("([a-zA-Z0-9]){1,128}");
private static final String POLICIES = "policyDocuments failed to satisfy constraint: ";
private static final String TTL_RANGE = " failed to satisfy constraint: Member must be greater than 5 minutes and less than 24 hours.";
private final IotAuthorizerService authorizers;
private final LambdaService lambdaService;
private final ObjectMapper objectMapper;
private final ObjectReader strictReader;
private final RegionResolver regionResolver;
/**
* What a WebSocket upgrade carried: the header names lower-cased, the raw query without its
* {@code ?} ({@code ""} when there was none), the server name, null unless it came over TLS, and
* the client's IP address, as the broker sees only the bridge's loopback socket.
*/
record WebSocketUpgrade(Map<String, String> headers, String queryString, String serverName, String sourceIp) {
}
@Inject
public IotCustomAuthorizer(IotAuthorizerService authorizers, LambdaService lambdaService, ObjectMapper objectMapper,
RegionResolver regionResolver) {
this.authorizers = authorizers;
this.lambdaService = lambdaService;
this.objectMapper = objectMapper;
this.strictReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.regionResolver = regionResolver;
}
/** TestInvokeAuthorizer: the request checks AWS makes before invoking, then the function's checked answer. */
public ObjectNode testInvoke(String name, JsonNode request, String region) {
String token = request.path("token").asText(null);
String signature = request.path("tokenSignature").asText(null);
String queryString = request.path("httpContext").path("queryString").asText(null);
if ("".equals(token)) {
throw IotAuthorizerService.constraint("token", "Member must have length greater than or equal to 1");
}
if (token != null && token.length() > 6144) {
throw IotAuthorizerService.constraint("token", "Member must have length less than or equal to 6144");
}
if (signature != null && !BASE64.matcher(signature).matches()) {
throw IotAuthorizerService.constraint("tokenSignature", "Member must satisfy regular expression pattern: " + BASE64);
}
if (signature != null && signature.length() > 2560) {
throw IotAuthorizerService.constraint("tokenSignature", "Member must have length less than or equal to 2560");
}
if ("".equals(queryString)) {
throw IotAuthorizerService.constraint("httpContext.queryString", "Member must have length greater than or equal to 1");
}
IotAuthorizer authorizer = authorizers.describeAuthorizer(name, region);
ObjectNode protocolData = objectMapper.createObjectNode();
for (String protocol : List.of("tls", "mqtt", "http")) {
JsonNode context = request.path(protocol + "Context");
if (context.isObject()) {
// ponytail: a context goes to the function as sent, members in request order, which SDKs send in model order.
// Nested members are not checked against the model's length and type constraints, only those measured above.
protocolData.set(protocol, context);
}
}
if ((token == null) != (signature == null)) {
throw IotAuthorizerService.invalid("Request must provide both token and tokenSignature together.");
}
if (token != null) {
if (!protocolData.isEmpty()) {
throw IotAuthorizerService.invalid("Request cannot have token and Http/Mqtt/Tls context.");
}
if (authorizer.isSigningDisabled()) {
throw IotAuthorizerService.invalid("Token and token signature provided but signing is disabled for the authorizer.");
}
return invoke(authorizer, event(null, verifiedToken(authorizer, token, signature)));
}
if (protocolData.isEmpty()) {
throw IotAuthorizerService.invalid("Request must have Http/Mqtt/Tls context.");
}
if (queryString != null && !queryString.startsWith("?")) {
throw IotAuthorizerService.invalid("Invalid arguments in the call");
}
Map<String, String> headers = new LinkedHashMap<>();
protocolData.path("http").path("headers").properties().forEach(header -> headers.put(header.getKey(), header.getValue().asText()));
Map<String, String> params = params(protocolData.path("mqtt").path("username").asText(null), headers, queryString);
return invoke(authorizer, event(protocolData, signedToken(authorizer, params)));
}
/** The authorizer an MQTT CONNECT names in its username query, the WebSocket URL query or an upgrade header; null when none. */
static String authorizerName(String username, WebSocketUpgrade upgrade) {
return params(username, upgrade).get(NAME_PARAM);
}
/**
* The policies an MQTT CONNECT through the named authorizer is admitted with. None when the
* authorizer is not ACTIVE, which never invokes the function, or when the function denies or
* returns no policy; an {@link AwsException} when the authorizer does not exist, a signature
* does not verify (the function is not invoked) or the answer is one TestInvokeAuthorizer rejects.
*/
List<String> connectPolicies(String name, String clientId, String username, String password, WebSocketUpgrade upgrade) {
// ponytail: the broker has no request context, so a connection finds authorizers in the default account and region.
IotAuthorizer authorizer = authorizers.describeAuthorizer(name, regionResolver.getDefaultRegion());
if (!"ACTIVE".equals(authorizer.getStatus())) {
return List.of();
}
ObjectNode protocolData = objectMapper.createObjectNode();
if (upgrade != null && upgrade.serverName() != null) {
protocolData.putObject("tls").put("serverName", upgrade.serverName());
}
ObjectNode mqtt = protocolData.putObject("mqtt");
if (username != null) {
mqtt.put("username", username);
}
if (password != null) {
// ponytail: Vert.x hands the password over as UTF-8 text, so bytes that are not UTF-8 reach the function altered.
mqtt.put("password", Base64.getEncoder().encodeToString(password.getBytes(StandardCharsets.UTF_8)));
}
mqtt.put("clientId", clientId);
if (upgrade != null) {
ObjectNode http = protocolData.putObject("http");
http.set("headers", objectMapper.valueToTree(upgrade.headers()));
http.put("queryString", upgrade.queryString());
}
ObjectNode answer = invoke(authorizer, event(protocolData, signedToken(authorizer, params(username, upgrade))));
if (!answer.path("isAuthenticated").booleanValue()) {
return List.of();
}
List<String> policies = new ArrayList<>();
answer.path("policyDocuments").forEach(policy -> policies.add(policy.asText()));
return policies;
}
private ObjectNode event(ObjectNode protocolData, String token) {
ObjectNode event = objectMapper.createObjectNode();
if (protocolData != null) {
event.set("protocolData", protocolData);
ArrayNode protocols = event.putArray("protocols");
for (String protocol : List.of("tls", "http", "mqtt")) {
if (protocolData.has(protocol)) {
protocols.add(protocol);
}
}
}
if (token != null) {
event.put("token", token);
}
event.put("signatureVerified", token != null);
event.putObject("connectionMetadata").put("id", UUID.randomUUID().toString());
return event;
}
/** Invokes the function and checks its answer as AWS does, returning the TestInvokeAuthorizer body. */
private ObjectNode invoke(IotAuthorizer authorizer, ObjectNode event) {
InvokeResult result = lambdaService.invokeArn(authorizer.getAuthorizerFunctionArn(),
event.toString().getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);
JsonNode answer = readJson(result.getPayload());
if (result.getFunctionError() != null) {
throw invalidResponse("Lambda function encountered error in execution: " + answer.path("errorMessage").asText()
+ ": " + answer.path("errorType").asText());
}
if (!answer.path("isAuthenticated").isBoolean()) {
throw invalidResponse("Lambda invocation result is in invalid format");
}
String principalId = answer.path("principalId").asText(null);
if (principalId == null || !PRINCIPAL_ID.matcher(principalId).matches()) {
throw invalidResponse(principalId + " at principalId failed to satisfy constraint: Member must satisfy " + PRINCIPAL_ID);
}
JsonNode policies = answer.path("policyDocuments");
if (!policies.isArray()) {
throw invalidResponse(POLICIES + "List of policies cannot be null.");
}
if (policies.size() > 10) {
throw invalidResponse(POLICIES + "Number of policies allowed cannot exceed 10");
}
ArrayNode documents = objectMapper.createArrayNode();
for (JsonNode policy : policies) {
String document = policy.isTextual() ? policy.asText() : policy.toString();
// ponytail: size counts characters and syntax means a JSON object; AWS's exact rules are unmeasured.
if (document.length() > 2048) {
throw invalidResponse(POLICIES + "Size of a policy document cannot exceeds hard limit of 2048");
}
if (!readJson(document.getBytes(StandardCharsets.UTF_8)).isObject()) {
throw invalidResponse(POLICIES + "Policy document is Malformed: Invalid policy syntax.");
}
documents.add(document);
}
int refresh = ttl(answer, "refreshAfterInSeconds", 300);
int disconnect = ttl(answer, "disconnectAfterInSeconds", 86400);
ObjectNode response = objectMapper.createObjectNode();
response.put("disconnectAfterInSeconds", disconnect);
response.put("isAuthenticated", answer.path("isAuthenticated").booleanValue());
response.set("policyDocuments", documents);
response.put("principalId", principalId);
response.put("refreshAfterInSeconds", refresh);
return response;
}
/** A TTL the function returned, or its default; AWS accepts 300 to 86400 inclusive whatever its message says. */
private static int ttl(JsonNode answer, String field, int fallback) {
JsonNode value = answer.path(field);
if (value.isMissingNode() || value.isNull()) {
return fallback;
}
if (!value.canConvertToInt() || value.asInt() < 300 || value.asInt() > 86400) {
throw invalidResponse(value.asText() + " at " + field + TTL_RANGE);
}
return value.asInt();
}
private JsonNode readJson(byte[] json) {
try {
JsonNode node = strictReader.readTree(json);
return node == null ? MissingNode.getInstance() : node;
} catch (IOException | IllegalArgumentException ignored) {
// Not JSON: the checks that follow report the answer the way AWS does.
return MissingNode.getInstance();
}
}
/** The verified token of a signed authorizer, or null for one with signing disabled. */
private static String signedToken(IotAuthorizer authorizer, Map<String, String> params) {
return authorizer.isSigningDisabled() ? null
: verifiedToken(authorizer, params.get(authorizer.getTokenKeyName()), params.get(SIGNATURE_PARAM));
}
/** The token, once an SHA256withRSA signature over it verifies against one of the authorizer's keys. */
private static String verifiedToken(IotAuthorizer authorizer, String token, String signature) {
if (token == null || signature == null) {
// AWS answers a signed authorizer without its token or signature with a null message.
throw new AwsException("InvalidRequestException", null, 400);
}
for (String pem : authorizer.getTokenSigningPublicKeys().values()) {
try {
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(IotAuthorizerService.rsaPublicKey(pem));
verifier.update(token.getBytes(StandardCharsets.UTF_8));
if (verifier.verify(Base64.getDecoder().decode(signature))) {
return token;
}
} catch (GeneralSecurityException | IllegalArgumentException e) {
LOG.debugv("Token signature for authorizer {0} did not verify: {1}", authorizer.getAuthorizerName(), e.getMessage());
}
}
throw IotAuthorizerService.invalid("Token signature mismatch for authorizer " + authorizer.getAuthorizerName());
}
private static Map<String, String> params(String username, WebSocketUpgrade upgrade) {
return upgrade == null ? params(username, Map.of(), null) : params(username, upgrade.headers(), upgrade.queryString());
}
/**
* The parameters a request carries for custom authentication: the query on the MQTT username,
* then the query string, then the headers, the first one naming a parameter winning.
*/
private static Map<String, String> params(String username, Map<String, String> headers, String queryString) {
// ponytail: names match case-insensitively in every source; precedence between sources is unmeasured on AWS.
Map<String, String> params = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
int usernameQuery = username == null ? -1 : username.indexOf('?');
if (usernameQuery >= 0) {
addQuery(params, username.substring(usernameQuery + 1));
}
if (queryString != null) {
addQuery(params, queryString.startsWith("?") ? queryString.substring(1) : queryString);
}
headers.forEach(params::putIfAbsent);
return params;
}
private static void addQuery(Map<String, String> params, String query) {
for (String pair : query.split("&")) {
int equals = pair.indexOf('=');
if (equals > 0) {
params.putIfAbsent(urlDecoded(pair.substring(0, equals)), urlDecoded(pair.substring(equals + 1)));
}
}
}
private static String urlDecoded(String value) {
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8);
} catch (IllegalArgumentException ignored) {
// A malformed escape is kept as sent: decoding it must not fail a CONNECT that names no authorizer.
return value;
}
}
private static AwsException invalidResponse(String message) {
return new AwsException("InvalidResponseException", message, 400);
}
}
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.services.iot.model.IotRetainedMessage;
import io.netty.handler.codec.mqtt.MqttConnectReturnCode;
import io.netty.handler.codec.mqtt.MqttProperties;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
@@ -49,6 +50,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@@ -118,6 +120,7 @@ public class IotMqttBrokerService implements Resettable {
private final EmulatorConfig config;
private final Vertx vertx;
private final Instance<IotService> iotService;
private final IotCustomAuthorizer customAuthorizer;
private final TlsConfigurationRegistry tlsRegistry;
final WorkerExecutor ruleWorker;
private final Map<String, ClientSession> sessionsByClient = new ConcurrentHashMap<>();
@@ -130,16 +133,18 @@ public class IotMqttBrokerService implements Resettable {
* the one it was admitted under.
*/
private final AtomicLong ruleState = new AtomicLong();
private final Map<SocketAddress, IotCustomAuthorizer.WebSocketUpgrade> webSocketUpgrades = new ConcurrentHashMap<>();
private MqttServer server;
private MqttServer tlsServer;
private ReloadingKeyManager keyManager;
@Inject
public IotMqttBrokerService(EmulatorConfig config, Vertx vertx, Instance<IotService> iotService,
TlsConfigurationRegistry tlsRegistry) {
IotCustomAuthorizer customAuthorizer, TlsConfigurationRegistry tlsRegistry) {
this.config = config;
this.vertx = vertx;
this.iotService = iotService;
this.customAuthorizer = customAuthorizer;
this.tlsRegistry = tlsRegistry;
this.ruleWorker = vertx.createSharedWorkerExecutor("floci-iot-mqtt-rules", 1);
}
@@ -325,6 +330,15 @@ public class IotMqttBrokerService implements Resettable {
ruleState.updateAndGet(state -> (state & reason) == 0 ? state : (state & ~reason) + RULE_STATE_STEP);
}
/**
* The WebSocket bridge's upgrades, keyed by the address its connection to the plaintext
* listener comes from: put before the first frame is piped, taken by that connection's CONNECT,
* dropped when the bridge session ends. A method, as the bridge holds a client proxy.
*/
Map<SocketAddress, IotCustomAuthorizer.WebSocketUpgrade> webSocketUpgrades() {
return webSocketUpgrades;
}
public synchronized boolean isRunning() {
return server != null;
}
@@ -368,7 +382,7 @@ public class IotMqttBrokerService implements Resettable {
* anything else is answered with CONNACK not authorized (return code 5, reason code 0x87 on
* MQTT 5) and never becomes a session, so a client already holding that client id keeps its
* connection. The plaintext listener, which the WebSocket bridge also lands on, stays open to
* every client.
* every client except one that names a custom authorizer, see {@link #authorizeCustom}.
*/
void handleEndpoint(MqttEndpoint endpoint, boolean verifyDevice) {
String clientId = endpoint.clientIdentifier();
@@ -383,7 +397,60 @@ public class IotMqttBrokerService implements Resettable {
: MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
return;
}
} else {
IotCustomAuthorizer.WebSocketUpgrade upgrade = remoteAddress == null ? null : webSocketUpgrades.remove(remoteAddress);
String username = endpoint.auth() == null ? null : endpoint.auth().getUsername();
String authorizerName = IotCustomAuthorizer.authorizerName(username, upgrade);
if (authorizerName != null) {
authorizeCustom(endpoint, authorizerName, upgrade, upgrade == null ? sourceIp : upgrade.sourceIp());
return;
}
}
admit(endpoint, principal);
}
/**
* A CONNECT naming a custom authorizer is admitted only when the authorizer's function allows
* it and the policies it returns allow {@code iot:Connect} for the client id. The function runs
* off the event loop. A refusal closes an MQTT 3.1.1 connection without a CONNACK and answers
* MQTT 5 with reason code 0x87, as AWS IoT does.
*/
private void authorizeCustom(MqttEndpoint endpoint, String authorizerName, IotCustomAuthorizer.WebSocketUpgrade upgrade,
String sourceIp) {
String clientId = endpoint.clientIdentifier();
String username = endpoint.auth() == null ? null : endpoint.auth().getUsername();
String password = endpoint.auth() == null ? null : endpoint.auth().getPassword();
String serverName = upgrade == null ? null : upgrade.serverName();
AtomicBoolean closed = new AtomicBoolean();
endpoint.closeHandler(ignored -> closed.set(true));
vertx.executeBlocking(() -> {
List<String> policies = customAuthorizer.connectPolicies(authorizerName, clientId, username, password, upgrade);
return iotService.get().isConnectAllowedBy(policies, clientId, sourceIp, serverName);
}, false).onComplete(decision -> {
if (closed.get()) {
return;
}
if (decision.succeeded() && decision.result()) {
admit(endpoint, null);
return;
}
LOG.debugv("IoT MQTT client {0} refused by custom authorizer {1}: {2}", clientId, authorizerName,
decision.failed() ? decision.cause().getMessage() : "iot:Connect is not allowed");
if (endpoint.protocolVersion() != 5) {
endpoint.close();
return;
}
MqttProperties properties = new MqttProperties();
properties.add(new MqttProperties.StringProperty(MqttProperties.MqttPropertyType.REASON_STRING.value(),
"CONNACK:Client is not authenticated/authorized to send the message:" + UUID.randomUUID()));
endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED_5, properties);
});
}
private void admit(MqttEndpoint endpoint, String principal) {
String clientId = endpoint.clientIdentifier();
SocketAddress remoteAddress = endpoint.remoteAddress();
String sourceIp = remoteAddress == null ? null : remoteAddress.host();
ClientSession session = new ClientSession(
clientId,
endpoint,
@@ -425,7 +492,7 @@ public class IotMqttBrokerService implements Resettable {
return null;
}
String certificateArn = device.get().certificate().getCertificateArn();
if (!iotService.get().isConnectAllowed(device.get(), clientId, sourceIp, requestedServerName(endpoint))) {
if (!iotService.get().isConnectAllowed(device.get(), clientId, sourceIp, requestedServerName(endpoint.sslSession()))) {
LOG.debugv("IoT MQTT TLS client {0} refused: iot:Connect is not allowed for {1}", clientId, certificateArn);
return null;
}
@@ -460,8 +527,8 @@ public class IotMqttBrokerService implements Resettable {
* {@code iot:DomainName}. An address literal is not a domain name: some clients send the
* host they dialled as SNI even when it is an IP.
*/
private static String requestedServerName(MqttEndpoint endpoint) {
if (!(endpoint.sslSession() instanceof ExtendedSSLSession session)) {
static String requestedServerName(SSLSession sslSession) {
if (!(sslSession instanceof ExtendedSSLSession session)) {
return null;
}
return session.getRequestedServerNames().stream()
@@ -5,6 +5,7 @@ import io.vertx.core.Vertx;
import io.vertx.core.http.ServerWebSocket;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetSocket;
import io.vertx.core.net.SocketAddress;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
@@ -12,6 +13,9 @@ import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/**
@@ -19,8 +23,10 @@ import java.util.concurrent.atomic.AtomicBoolean;
* IoT uses for browser clients, the Device SDK's WebSocket transport and secure tunnelling. Frames
* are piped byte for byte to the broker's plaintext listener, so every broker feature and every
* authorization rule applies without a second code path. No client certificate is involved: on
* AWS this path authenticates by SigV4 or a custom authorizer, and the broker stays permissive
* for it.
* AWS this path authenticates by SigV4 or a custom authorizer. The broker enforces a custom
* authorizer named in the MQTT username, the URL query or an upgrade header, and stays permissive
* otherwise; the upgrade's headers, query, server name and client address reach it through
* {@link IotMqttBrokerService#webSocketUpgrades()}.
*
* <p>Everything for one session runs on the event loop of the WebSocket's connection, the
* broker socket included, so the handlers below never race each other.
@@ -92,7 +98,12 @@ public class IotMqttWebSocketBridge {
socket.close();
return;
}
new BridgeSession(ws, socket).start();
// Registered before start() lets the first frame through, so it is there when the CONNECT
// reaches the broker; removed only if still this very instance, as the address can be reused.
SocketAddress bridgeAddress = socket.localAddress();
IotCustomAuthorizer.WebSocketUpgrade upgrade = upgradeOf(ws);
broker.webSocketUpgrades().put(bridgeAddress, upgrade);
new BridgeSession(ws, socket, forgetting(broker.webSocketUpgrades(), bridgeAddress, upgrade)).start();
})
.onFailure(error -> {
LOG.warnv("MQTT WebSocket bridge could not reach the broker on {0}:{1}: {2}",
@@ -101,15 +112,43 @@ public class IotMqttWebSocketBridge {
});
}
/** Drops the session's upgrade unless the address already carries a newer session's. */
static Runnable forgetting(Map<SocketAddress, IotCustomAuthorizer.WebSocketUpgrade> upgrades, SocketAddress address,
IotCustomAuthorizer.WebSocketUpgrade upgrade) {
return () -> upgrades.computeIfPresent(address, (key, current) -> current == upgrade ? null : current);
}
/**
* The upgrade as AWS hands it to a custom authorizer; the server name only over TLS, from SNI or
* else the Host header. The client's address rides along for the broker's policy evaluation.
*/
private static IotCustomAuthorizer.WebSocketUpgrade upgradeOf(ServerWebSocket ws) {
Map<String, String> headers = new LinkedHashMap<>();
// ponytail: a repeated header keeps its last value.
ws.headers().forEach(header -> headers.put(header.getKey().toLowerCase(Locale.ROOT), header.getValue()));
String serverName = null;
if (ws.isSsl()) {
serverName = IotMqttBrokerService.requestedServerName(ws.sslSession());
if (serverName == null && ws.authority() != null && !IotMqttBrokerService.isAddressLiteral(ws.authority().host())) {
serverName = ws.authority().host();
}
}
SocketAddress client = ws.remoteAddress();
return new IotCustomAuthorizer.WebSocketUpgrade(headers, ws.query() == null ? "" : ws.query(), serverName,
client == null ? null : client.host());
}
static final class BridgeSession {
private final ServerWebSocket webSocket;
private final NetSocket socket;
private final Runnable onClose;
private final AtomicBoolean closed = new AtomicBoolean();
BridgeSession(ServerWebSocket webSocket, NetSocket socket) {
BridgeSession(ServerWebSocket webSocket, NetSocket socket, Runnable onClose) {
this.webSocket = webSocket;
this.socket = socket;
this.onClose = onClose;
}
void start() {
@@ -162,7 +201,7 @@ public class IotMqttWebSocketBridge {
}
private void close(short code, String reason) {
if (closed.compareAndSet(false, true)) {
if (markClosed()) {
socket.close();
if (!webSocket.isClosed()) {
webSocket.close(code, reason);
@@ -171,16 +210,25 @@ public class IotMqttWebSocketBridge {
}
private void closeSocket() {
if (closed.compareAndSet(false, true)) {
if (markClosed()) {
socket.close();
}
}
private void closeWebSocket() {
if (closed.compareAndSet(false, true) && !webSocket.isClosed()) {
if (markClosed() && !webSocket.isClosed()) {
// ponytail: on a custom-auth refusal AWS sends an empty close frame (MQTT 3.1.1) or no close frame (MQTT 5); Vert.x has no public API for either, so this sends status 1000.
webSocket.close();
}
}
private boolean markClosed() {
if (!closed.compareAndSet(false, true)) {
return false;
}
onClose.run();
return true;
}
}
/** The broker binds {@code 0.0.0.0} by default, which is not a connect target; loopback is. */
@@ -495,14 +495,30 @@ public class IotService {
return false;
}
List<String> documents = attachedPolicyDocuments(certificate.getCertificateArn(), device.region(), device.accountId());
return isConnectAllowed(documents, connectionVariables(device, clientId, sourceIp, domainName),
device.region(), device.accountId(), clientId);
}
/**
* Decides {@code iot:Connect} for a client a custom authorizer admitted, from the policies its
* function returned, with the basic connection variables: there is no certificate, so the thing
* variables do not resolve.
*/
public boolean isConnectAllowedBy(List<String> documents, String clientId, String sourceIp, String domainName) {
// ponytail: the broker has no request context, so a custom-auth client connects to the default account and region.
return isConnectAllowed(documents, basicConnectionVariables(clientId, sourceIp, domainName),
regionResolver.getDefaultRegion(), regionResolver.getDefaultAccountId(), clientId);
}
private boolean isConnectAllowed(List<String> documents, Map<String, String> variables, String region, String accountId,
String clientId) {
if (documents.isEmpty()) {
return false;
}
Map<String, String> variables = connectionVariables(device, clientId, sourceIp, domainName);
List<String> resolved = documents.stream().map(document -> resolvePolicyVariables(document, variables)).toList();
Map<String, List<String>> conditionContext = new LinkedHashMap<>();
variables.forEach((key, value) -> conditionContext.put(key, List.of(value)));
String clientArn = AwsArnUtils.Arn.of("iot", device.region(), device.accountId(), "client/" + clientId).toString();
String clientArn = AwsArnUtils.Arn.of("iot", region, accountId, "client/" + clientId).toString();
return policyEvaluator.evaluate(CallerContext.of(resolved), null, "iot:Connect", clientArn, conditionContext)
== IamPolicyEvaluator.Decision.ALLOW;
}
@@ -533,14 +549,7 @@ public class IotService {
* the client id names a thing attached to the certificate, as on AWS.
*/
private Map<String, String> connectionVariables(RegisteredDevice device, String clientId, String sourceIp, String domainName) {
Map<String, String> variables = new LinkedHashMap<>();
variables.put("iot:ClientId", clientId);
if (sourceIp != null) {
variables.put("aws:SourceIp", sourceIp);
}
if (domainName != null) {
variables.put("iot:DomainName", domainName);
}
Map<String, String> variables = basicConnectionVariables(clientId, sourceIp, domainName);
Optional<Thing> thing = getForAccount(thingStore, device.accountId(), thingKey(device.region(), clientId));
boolean attached = thing.isPresent()
&& getForAccount(thingPrincipalStore, device.accountId(), thingPrincipalKey(device.region(), clientId))
@@ -556,6 +565,18 @@ public class IotService {
return variables;
}
private static Map<String, String> basicConnectionVariables(String clientId, String sourceIp, String domainName) {
Map<String, String> variables = new LinkedHashMap<>();
variables.put("iot:ClientId", clientId);
if (sourceIp != null) {
variables.put("aws:SourceIp", sourceIp);
}
if (domainName != null) {
variables.put("iot:DomainName", domainName);
}
return variables;
}
/**
* Substitutes the connection's variables into every string of the document on the parsed tree,
* so a client id is never read as JSON. A statement still holding a variable Floci cannot