From 6819bce49356fc957d4cbf8db24fa8c05fd27ccd Mon Sep 17 00:00:00 2001 From: nblomquist Date: Tue, 19 May 2026 22:53:30 -0400 Subject: [PATCH] feat(kms): implement GenerateMac and VerifyMac (#927) * feat(kms): implement GenerateMac and VerifyMac * fix(kms): remove unused MAC message type handling * test(kms): add MAC JSON handler integration coverage * fix(kms): avoid duplicate MAC key resolution --- .../floci/services/kms/KmsJsonHandler.java | 31 +++++ .../floci/services/kms/KmsService.java | 99 ++++++++++++++++ .../services/kms/KmsIntegrationTest.java | 111 ++++++++++++++++++ .../floci/services/kms/KmsServiceTest.java | 102 ++++++++++++++++ 4 files changed, 343 insertions(+) create mode 100644 src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java index 60e9d9ea0c..46dd02093a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java @@ -45,6 +45,8 @@ public class KmsJsonHandler { case "GenerateDataKeyWithoutPlaintext" -> handleGenerateDataKeyWithoutPlaintext(request, region); case "Sign" -> handleSign(request, region); case "Verify" -> handleVerify(request, region); + case "GenerateMac" -> handleGenerateMac(request, region); + case "VerifyMac" -> handleVerifyMac(request, region); case "CreateAlias" -> handleCreateAlias(request, region); case "DeleteAlias" -> handleDeleteAlias(request, region); case "ListAliases" -> handleListAliases(request, region); @@ -246,6 +248,35 @@ public class KmsJsonHandler { return Response.ok(response).build(); } + private Response handleGenerateMac(JsonNode request, String region) { + String keyId = request.path("KeyId").asText(); + byte[] message = Base64.getDecoder().decode(request.path("Message").asText()); + String algorithm = request.path("MacAlgorithm").asText(); + + KmsService.GenerateMacResult result = service.generateMacAndResolveKey(keyId, message, algorithm, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("KeyId", result.keyArn()); + response.put("Mac", Base64.getEncoder().encodeToString(result.mac())); + response.put("MacAlgorithm", algorithm); + return Response.ok(response).build(); + } + + private Response handleVerifyMac(JsonNode request, String region) { + String keyId = request.path("KeyId").asText(); + byte[] message = Base64.getDecoder().decode(request.path("Message").asText()); + byte[] mac = Base64.getDecoder().decode(request.path("Mac").asText()); + String algorithm = request.path("MacAlgorithm").asText(); + + KmsService.VerifyMacResult result = service.verifyMacAndResolveKey(keyId, message, mac, algorithm, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("KeyId", result.keyArn()); + response.put("MacAlgorithm", algorithm); + response.put("MacValid", true); + return Response.ok(response).build(); + } + private Response handleCreateAlias(JsonNode request, String region) { service.createAlias(request.path("AliasName").asText(), request.path("TargetKeyId").asText(), region); return Response.ok(objectMapper.createObjectNode()).build(); diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java index 89cf89ec9a..2f55b5d23d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java @@ -30,6 +30,8 @@ import org.bouncycastle.jce.ECNamedCurveTable; import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; import org.jboss.logging.Logger; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayOutputStream; import java.math.BigInteger; import java.nio.ByteBuffer; @@ -333,6 +335,10 @@ public class KmsService { private static final String BLOB_PREFIX_V2 = "kms:v2:"; private static final String BLOB_PREFIX_V1 = "kms:"; private static final int NONCE_BYTES = 8; + private static final int MIN_MAC_MESSAGE_BYTES = 1; + private static final int MAX_MAC_MESSAGE_BYTES = 4096; + private static final int MIN_MAC_BYTES = 1; + private static final int MAX_MAC_BYTES = 6144; private static final SecureRandom SECURE_RANDOM = new SecureRandom(); public byte[] encrypt(String keyId, byte[] plaintext, String region) { @@ -395,6 +401,10 @@ public class KmsService { public record DecryptResult(byte[] plaintext, String keyArn) {} + public record GenerateMacResult(byte[] mac, String keyArn) {} + + public record VerifyMacResult(String keyArn) {} + private record ParsedBlob(String keyId, String nonce, String contextFingerprint, String payload) {} private static ParsedBlob parseBlob(byte[] ciphertext) { @@ -506,6 +516,95 @@ public class KmsService { } } + public byte[] generateMac(String keyId, byte[] message, String algorithm, String region) { + KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region); + return generateMac(kmsKey, message, algorithm); + } + + public GenerateMacResult generateMacAndResolveKey(String keyId, byte[] message, String algorithm, String region) { + KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region); + return new GenerateMacResult(generateMac(kmsKey, message, algorithm), kmsKey.getArn()); + } + + private byte[] generateMac(KmsKey kmsKey, byte[] message, String algorithm) { + validateMacMessageLength(message); + + try { + byte[] keyBytes = Base64.getDecoder().decode(kmsKey.getPrivateKeyEncoded()); + String jcaAlgorithm = mapMacAlgorithm(algorithm); + Mac mac = Mac.getInstance(jcaAlgorithm); + mac.init(new SecretKeySpec(keyBytes, jcaAlgorithm)); + mac.update(message); + return mac.doFinal(); + } catch (AwsException e) { + throw e; + } catch (Exception e) { + throw new AwsException("InternalFailure", "Failed to generate MAC: " + e.getMessage(), 500); + } + } + + public void verifyMac(String keyId, byte[] message, byte[] mac, String algorithm, String region) { + validateMacLength(mac); + KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region); + verifyMac(kmsKey, message, mac, algorithm); + } + + public VerifyMacResult verifyMacAndResolveKey(String keyId, byte[] message, byte[] mac, String algorithm, String region) { + validateMacLength(mac); + KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region); + verifyMac(kmsKey, message, mac, algorithm); + return new VerifyMacResult(kmsKey.getArn()); + } + + private void verifyMac(KmsKey kmsKey, byte[] message, byte[] mac, String algorithm) { + byte[] expected = generateMac(kmsKey, message, algorithm); + if (!MessageDigest.isEqual(expected, mac)) { + throw new AwsException("KMSInvalidMacException", "The MAC is not valid.", 400); + } + } + + private KmsKey validateMacOperationKey(String keyId, String algorithm, String region) { + KmsKey kmsKey = resolveKey(keyId, region); + String spec = kmsKey.getCustomerMasterKeySpec(); + if (!isHmac(spec) || !"GENERATE_VERIFY_MAC".equals(kmsKey.getKeyUsage())) { + throw new AwsException("InvalidKeyUsageException", + "MAC operations require an HMAC key with KeyUsage GENERATE_VERIFY_MAC.", 400); + } + + String expectedAlgorithm = macAlgorithmFor(spec); + if (!Objects.equals(expectedAlgorithm, algorithm)) { + throw new AwsException("InvalidKeyUsageException", + "MacAlgorithm " + algorithm + " is not valid for KeySpec " + spec + ".", 400); + } + return kmsKey; + } + + private String mapMacAlgorithm(String awsAlgo) { + return switch (awsAlgo) { + case "HMAC_SHA_224" -> "HmacSHA224"; + case "HMAC_SHA_256" -> "HmacSHA256"; + case "HMAC_SHA_384" -> "HmacSHA384"; + case "HMAC_SHA_512" -> "HmacSHA512"; + default -> throw new AwsException("InvalidMacAlgorithmException", "Unsupported MAC algorithm: " + awsAlgo, 400); + }; + } + + private static void validateMacMessageLength(byte[] message) { + int length = message == null ? 0 : message.length; + if (length < MIN_MAC_MESSAGE_BYTES || length > MAX_MAC_MESSAGE_BYTES) { + throw new AwsException("ValidationException", + "Message must be between 1 and 4096 bytes for MAC operations.", 400); + } + } + + private static void validateMacLength(byte[] mac) { + int length = mac == null ? 0 : mac.length; + if (length < MIN_MAC_BYTES || length > MAX_MAC_BYTES) { + throw new AwsException("ValidationException", + "Mac must be between 1 and 6144 bytes for VerifyMac.", 400); + } + } + private PrivateKey loadPrivateKey(String encoded, String spec) throws Exception { byte[] decoded = Base64.getDecoder().decode(encoded); if (isSecgP256k1(spec)) { diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java new file mode 100644 index 0000000000..be19a94c17 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java @@ -0,0 +1,111 @@ +package io.github.hectorvent.floci.services.kms; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +class KmsIntegrationTest { + + private static final String KMS_CONTENT_TYPE = "application/x-amz-json-1.1"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void generateMacAndVerifyMacRoundTripThroughJsonHandler() { + String keyId = given() + .header("X-Amz-Target", "TrentService.CreateKey") + .contentType(KMS_CONTENT_TYPE) + .body(""" + { + "Description": "integration-hmac", + "KeyUsage": "GENERATE_VERIFY_MAC", + "CustomerMasterKeySpec": "HMAC_256" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("KeyMetadata.KeyId", notNullValue()) + .body("KeyMetadata.Arn", startsWith("arn:aws:kms:")) + .body("KeyMetadata.KeyUsage", equalTo("GENERATE_VERIFY_MAC")) + .body("KeyMetadata.CustomerMasterKeySpec", equalTo("HMAC_256")) + .extract().jsonPath().getString("KeyMetadata.KeyId"); + + String message = Base64.getEncoder().encodeToString( + "kms integration mac message".getBytes(StandardCharsets.UTF_8)); + String mac = given() + .header("X-Amz-Target", "TrentService.GenerateMac") + .contentType(KMS_CONTENT_TYPE) + .body(""" + { + "KeyId": "%s", + "Message": "%s", + "MacAlgorithm": "HMAC_SHA_256" + } + """.formatted(keyId, message)) + .when() + .post("/") + .then() + .statusCode(200) + .body("KeyId", startsWith("arn:aws:kms:")) + .body("Mac", notNullValue()) + .body("MacAlgorithm", equalTo("HMAC_SHA_256")) + .extract().jsonPath().getString("Mac"); + + assertEquals(32, Base64.getDecoder().decode(mac).length); + + given() + .header("X-Amz-Target", "TrentService.VerifyMac") + .contentType(KMS_CONTENT_TYPE) + .body(""" + { + "KeyId": "%s", + "Message": "%s", + "Mac": "%s", + "MacAlgorithm": "HMAC_SHA_256" + } + """.formatted(keyId, message, mac)) + .when() + .post("/") + .then() + .statusCode(200) + .body("KeyId", startsWith("arn:aws:kms:")) + .body("MacAlgorithm", equalTo("HMAC_SHA_256")) + .body("MacValid", equalTo(true)); + + String differentMessage = Base64.getEncoder().encodeToString( + "different message".getBytes(StandardCharsets.UTF_8)); + + given() + .header("X-Amz-Target", "TrentService.VerifyMac") + .contentType(KMS_CONTENT_TYPE) + .body(""" + { + "KeyId": "%s", + "Message": "%s", + "Mac": "%s", + "MacAlgorithm": "HMAC_SHA_256" + } + """.formatted(keyId, differentMessage, mac)) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("KMSInvalidMacException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java index 30d88aacd5..4dcb08e56f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java @@ -657,6 +657,17 @@ class KmsServiceTest { assertEquals(spec, found.getCustomerMasterKeySpec()); } + @ParameterizedTest + @ValueSource(strings = {"HMAC_224", "HMAC_256", "HMAC_384", "HMAC_512"}) + void generateMacSupportsAllAdvertisedHmacSpecs(String spec) { + KmsKey key = kmsService.createKey("hmac key", "GENERATE_VERIFY_MAC", spec, null, Map.of(), REGION); + byte[] message = "floci-mac-probe".getBytes(StandardCharsets.UTF_8); + + byte[] mac = kmsService.generateMac(key.getKeyId(), message, KmsService.macAlgorithmFor(spec), REGION); + + assertEquals(expectedMacByteLength(spec), mac.length); + } + @Test void createHmacKey_requiresGenerateVerifyMacUsage() { AwsException ex = assertThrows(AwsException.class, () -> @@ -678,4 +689,95 @@ class KmsServiceTest { kmsService.getPublicKey(key.getKeyId(), REGION)); assertEquals("UnsupportedOperationException", ex.getErrorCode()); } + + @Test + void generateMacWithHmacKeyReturnsDeterministicMac() { + KmsKey key = kmsService.createKey("hmac key", "GENERATE_VERIFY_MAC", "HMAC_256", null, Map.of(), REGION); + byte[] message = "floci-mac-probe".getBytes(StandardCharsets.UTF_8); + + byte[] first = kmsService.generateMac(key.getKeyId(), message, "HMAC_SHA_256", REGION); + byte[] second = kmsService.generateMac(key.getKeyId(), message, "HMAC_SHA_256", REGION); + + assertEquals(32, first.length); + assertArrayEquals(first, second); + } + + @Test + void generateMacRejectsAlgorithmThatDoesNotMatchKeySpec() { + KmsKey key = kmsService.createKey("hmac key", "GENERATE_VERIFY_MAC", "HMAC_256", null, Map.of(), REGION); + byte[] message = "floci-mac-probe".getBytes(StandardCharsets.UTF_8); + + AwsException ex = assertThrows(AwsException.class, () -> + kmsService.generateMac(key.getKeyId(), message, "HMAC_SHA_512", REGION)); + + assertEquals("InvalidKeyUsageException", ex.getErrorCode()); + } + + @Test + void generateMacRejectsMessageOutsideAwsLengthBounds() { + KmsKey key = kmsService.createKey("hmac key", "GENERATE_VERIFY_MAC", "HMAC_256", null, Map.of(), REGION); + + AwsException empty = assertThrows(AwsException.class, () -> + kmsService.generateMac(key.getKeyId(), new byte[0], "HMAC_SHA_256", REGION)); + AwsException oversized = assertThrows(AwsException.class, () -> + kmsService.generateMac(key.getKeyId(), new byte[4097], "HMAC_SHA_256", REGION)); + + assertEquals("ValidationException", empty.getErrorCode()); + assertEquals("ValidationException", oversized.getErrorCode()); + } + + @Test + void verifyMacAcceptsMatchingMacAndRejectsMismatch() { + KmsKey key = kmsService.createKey("hmac key", "GENERATE_VERIFY_MAC", "HMAC_256", null, Map.of(), REGION); + byte[] message = "floci-mac-probe".getBytes(StandardCharsets.UTF_8); + byte[] mac = kmsService.generateMac(key.getKeyId(), message, "HMAC_SHA_256", REGION); + + assertDoesNotThrow(() -> kmsService.verifyMac(key.getKeyId(), message, mac, "HMAC_SHA_256", REGION)); + + byte[] tamperedMac = mac.clone(); + tamperedMac[0] ^= 1; + AwsException ex = assertThrows(AwsException.class, () -> + kmsService.verifyMac(key.getKeyId(), message, tamperedMac, "HMAC_SHA_256", REGION)); + + assertEquals("KMSInvalidMacException", ex.getErrorCode()); + } + + @Test + void verifyMacRejectsMacOutsideAwsLengthBounds() { + KmsKey key = kmsService.createKey("hmac key", "GENERATE_VERIFY_MAC", "HMAC_256", null, Map.of(), REGION); + byte[] message = "floci-mac-probe".getBytes(StandardCharsets.UTF_8); + + AwsException empty = assertThrows(AwsException.class, () -> + kmsService.verifyMac(key.getKeyId(), message, new byte[0], "HMAC_SHA_256", REGION)); + AwsException oversized = assertThrows(AwsException.class, () -> + kmsService.verifyMac(key.getKeyId(), message, new byte[6145], "HMAC_SHA_256", REGION)); + + assertEquals("ValidationException", empty.getErrorCode()); + assertEquals("ValidationException", oversized.getErrorCode()); + } + + @Test + void verifyMacRejectsMessageOutsideAwsLengthBounds() { + KmsKey key = kmsService.createKey("hmac key", "GENERATE_VERIFY_MAC", "HMAC_256", null, Map.of(), REGION); + byte[] validMessage = "floci-mac-probe".getBytes(StandardCharsets.UTF_8); + byte[] mac = kmsService.generateMac(key.getKeyId(), validMessage, "HMAC_SHA_256", REGION); + + AwsException empty = assertThrows(AwsException.class, () -> + kmsService.verifyMac(key.getKeyId(), new byte[0], mac, "HMAC_SHA_256", REGION)); + AwsException oversized = assertThrows(AwsException.class, () -> + kmsService.verifyMac(key.getKeyId(), new byte[4097], mac, "HMAC_SHA_256", REGION)); + + assertEquals("ValidationException", empty.getErrorCode()); + assertEquals("ValidationException", oversized.getErrorCode()); + } + + private static int expectedMacByteLength(String spec) { + return switch (spec) { + case "HMAC_224" -> 28; + case "HMAC_256" -> 32; + case "HMAC_384" -> 48; + case "HMAC_512" -> 64; + default -> -1; + }; + } }