fix(kms): non-deterministic Encrypt and EncryptionContext AAD validation (#825)

* fix(kms): non-deterministic Encrypt and EncryptionContext AAD validation

Two security-parity bugs in the KMS mock:

- Encrypt was deterministic: identical Plaintext + KeyId + EncryptionContext
  produced byte-identical CiphertextBlob, leaking plaintext equality. Real
  AWS derives a fresh AES-GCM key per call and is non-deterministic.

- Decrypt ignored EncryptionContext, so a ciphertext encrypted under
  {tenant: "1"} decrypted successfully under {tenant: "999"} (or no context
  at all). Real AWS binds EncryptionContext as AAD and fails with
  InvalidCiphertextException on any mismatch.

Switched the mock blob format to embed (a) a fresh 8-byte random nonce per
call and (b) a SHA-256 fingerprint of the canonicalized, sorted
EncryptionContext. Decrypt now rejects on fingerprint mismatch. Omitted
context and {} are interchangeable, matching AWS.

Threaded EncryptionContext through Encrypt / Decrypt / GenerateDataKey /
GenerateDataKeyWithoutPlaintext / ReEncrypt handlers (ReEncrypt honors
both SourceEncryptionContext and DestinationEncryptionContext).

Closes #816
Closes #817

* fix(kms): address review feedback on PR #825

- Accept legacy v1 blobs (kms:<keyId>:<base64>) in parseBlob, for
  back-compat with persistent stores that hold pre-v2 ciphertext.
- Cache SecureRandom as a static final field instead of allocating
  per Encrypt call.
- Replace the double-parseBlob pattern in handleDecrypt and
  handleReEncrypt with a new single-pass KmsService.decryptAndResolveKey
  method that returns plaintext + source key ARN in one record.
  decrypt() and decryptToKeyArn() remain independent primitives and
  do not delegate through the new composite.
- Add reEncryptHonorsSourceContext test asserting that wrong source
  context fails the decrypt half and that the destination blob is
  bound to destination context, not source.
- Add legacyV1BlobDecryptsForBackCompat test pinning the v1 fallback
  parser behavior (accepts empty/null context, rejects non-empty
  context, resolves source key ARN).
- Clean up inline fully-qualified class references in tests to use
  imports (Arrays, LinkedHashMap).

* test(kms): pin v1↔v2 prefix collision behavior

Locks in the documented limitation that a pre-PR v1 ciphertext encrypted
under an override-id of literally "v2" produces "kms:v2:<base64>", which
is indistinguishable by prefix from a malformed v2 blob and is rejected
by parseBlob with InvalidCiphertextException.

Trade-off, not a bug:
- Failure is loud (InvalidCiphertextException), not silent corruption.
- Conditions to hit are extremely narrow (persistent mode + override-id
  + key literally named "v2" + crossing the pre-PR upgrade boundary).
- Avoiding it would require either silently-lenient fallback parsing or
  a v2-prefix rename, both with their own trade-offs.

If a future refactor changes BLOB_PREFIX_V2 or adds fall-through parsing,
this test fails — prompting a deliberate decision rather than a silent
behavior change.
This commit is contained in:
Ahmed Soliman authored and GitHub committed 2026-05-14 07:12:29 -05:00
1 parent 6f57af3edc
commit 6a8c44fad5
3 files changed
+327 -32

No files matched your search

@@ -139,7 +139,8 @@ public class KmsJsonHandler {
private Response handleEncrypt(JsonNode request, String region) {
String keyId = request.path("KeyId").asText();
byte[] plaintext = Base64.getDecoder().decode(request.path("Plaintext").asText());
byte[] ciphertext = service.encrypt(keyId, plaintext, region);
Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));
byte[] ciphertext = service.encrypt(keyId, plaintext, context, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("CiphertextBlob", Base64.getEncoder().encodeToString(ciphertext));
@@ -149,16 +150,13 @@ public class KmsJsonHandler {
private Response handleDecrypt(JsonNode request, String region) {
byte[] ciphertext = Base64.getDecoder().decode(request.path("CiphertextBlob").asText());
byte[] plaintext = service.decrypt(ciphertext, region);
Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));
KmsService.DecryptResult result = service.decryptAndResolveKey(ciphertext, context, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("Plaintext", Base64.getEncoder().encodeToString(plaintext));
// In our mock, we don't strictly track which key was used for decryption from blob alone,
// but we could extract it from our mock format "kms:keyId:..."
String data = new String(ciphertext);
if (data.startsWith("kms:")) {
String keyId = data.split(":")[1];
response.put("KeyId", service.describeKey(keyId, region).getArn());
response.put("Plaintext", Base64.getEncoder().encodeToString(result.plaintext()));
if (result.keyArn() != null) {
response.put("KeyId", result.keyArn());
}
return Response.ok(response).build();
}
@@ -167,8 +165,9 @@ public class KmsJsonHandler {
String keyId = request.path("KeyId").asText();
String spec = request.path("KeySpec").asText(null);
int numberOfBytes = request.path("NumberOfBytes").asInt(0);
Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));
Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, region);
Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, context, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("Plaintext", Base64.getEncoder().encodeToString((byte[]) result.get("Plaintext")));
@@ -181,8 +180,9 @@ public class KmsJsonHandler {
String keyId = request.path("KeyId").asText();
String spec = request.path("KeySpec").asText(null);
int numberOfBytes = request.path("NumberOfBytes").asInt(0);
Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));
Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, region);
Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, context, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("CiphertextBlob", Base64.getEncoder().encodeToString((byte[]) result.get("CiphertextBlob")));
@@ -193,17 +193,28 @@ public class KmsJsonHandler {
private Response handleReEncrypt(JsonNode request, String region) {
byte[] ciphertext = Base64.getDecoder().decode(request.path("CiphertextBlob").asText());
String destKeyId = request.path("DestinationKeyId").asText();
Map<String, String> sourceContext = readEncryptionContext(request.path("SourceEncryptionContext"));
Map<String, String> destContext = readEncryptionContext(request.path("DestinationEncryptionContext"));
byte[] plaintext = service.decrypt(ciphertext, region);
byte[] newCiphertext = service.encrypt(destKeyId, plaintext, region);
KmsService.DecryptResult source = service.decryptAndResolveKey(ciphertext, sourceContext, region);
byte[] newCiphertext = service.encrypt(destKeyId, source.plaintext(), destContext, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("CiphertextBlob", Base64.getEncoder().encodeToString(newCiphertext));
response.put("KeyId", service.describeKey(destKeyId, region).getArn());
response.put("SourceKeyId", service.decryptToKeyArn(ciphertext, region));
response.put("SourceKeyId", source.keyArn());
return Response.ok(response).build();
}
private static Map<String, String> readEncryptionContext(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull() || !node.isObject()) {
return Map.of();
}
Map<String, String> result = new HashMap<>();
node.fields().forEachRemaining(e -> result.put(e.getKey(), e.getValue().asText()));
return result;
}
private Response handleSign(JsonNode request, String region) {
String keyId = request.path("KeyId").asText();
byte[] message = Base64.getDecoder().decode(request.path("Message").asText());
@@ -32,6 +32,7 @@ import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.*;
@@ -326,31 +327,121 @@ public class KmsService {
// ──────────────────────────── Crypto Ops (Mocks) ────────────────────────────
// v2 blob: kms:v2:<keyId>:<nonceHex>:<contextFingerprintHex>:<base64(plaintext)>
// Nonce makes Encrypt non-deterministic; contextFingerprint binds EncryptionContext as AAD.
// Legacy v1 (kms:<keyId>:<base64>) still accepted on Decrypt for persistent-store back-compat.
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 SecureRandom SECURE_RANDOM = new SecureRandom();
public byte[] encrypt(String keyId, byte[] plaintext, String region) {
return encrypt(keyId, plaintext, Map.of(), region);
}
public byte[] encrypt(String keyId, byte[] plaintext, Map<String, String> encryptionContext, String region) {
KmsKey kmsKey = resolveKey(keyId, region);
// Local mock: prefix with keyId and base64
String mock = "kms:" + kmsKey.getKeyId() + ":" + Base64.getEncoder().encodeToString(plaintext);
return mock.getBytes(StandardCharsets.UTF_8);
byte[] nonceBytes = new byte[NONCE_BYTES];
SECURE_RANDOM.nextBytes(nonceBytes);
String nonceHex = HexFormat.of().formatHex(nonceBytes);
String blob = BLOB_PREFIX_V2
+ kmsKey.getKeyId() + ":"
+ nonceHex + ":"
+ contextFingerprint(encryptionContext) + ":"
+ Base64.getEncoder().encodeToString(plaintext);
return blob.getBytes(StandardCharsets.UTF_8);
}
public byte[] decrypt(byte[] ciphertext, String region) {
String data = new String(ciphertext, StandardCharsets.UTF_8);
if (!data.startsWith("kms:")) {
return decrypt(ciphertext, Map.of(), region);
}
public byte[] decrypt(byte[] ciphertext, Map<String, String> encryptionContext, String region) {
ParsedBlob parsed = parseBlob(ciphertext);
if (!parsed.contextFingerprint.equals(contextFingerprint(encryptionContext))) {
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
}
String[] parts = data.split(":", 3);
if (parts.length < 3) throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
return Base64.getDecoder().decode(parts[2]);
return Base64.getDecoder().decode(parsed.payload);
}
public String decryptToKeyArn(byte[] ciphertext, String region) {
String data = new String(ciphertext, StandardCharsets.UTF_8);
if (data.startsWith("kms:")) {
String keyId = data.split(":")[1];
return resolveKey(keyId, region).getArn();
try {
return resolveKey(parseBlob(ciphertext).keyId, region).getArn();
} catch (AwsException e) {
return null;
}
}
/**
* Single-pass decrypt + source-key-ARN resolution. {@link #decrypt} and
* {@link #decryptToKeyArn} remain independent primitives — neither delegates here.
*/
public DecryptResult decryptAndResolveKey(byte[] ciphertext, Map<String, String> encryptionContext, String region) {
ParsedBlob parsed = parseBlob(ciphertext);
if (!parsed.contextFingerprint.equals(contextFingerprint(encryptionContext))) {
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
}
byte[] plaintext = Base64.getDecoder().decode(parsed.payload);
String keyArn;
try {
keyArn = resolveKey(parsed.keyId, region).getArn();
} catch (AwsException e) {
keyArn = null;
}
return new DecryptResult(plaintext, keyArn);
}
public record DecryptResult(byte[] plaintext, String keyArn) {}
private record ParsedBlob(String keyId, String nonce, String contextFingerprint, String payload) {}
private static ParsedBlob parseBlob(byte[] ciphertext) {
String data = new String(ciphertext, StandardCharsets.UTF_8);
if (data.startsWith(BLOB_PREFIX_V2)) {
// v2: keyId, nonce, contextFingerprint, payload
String[] parts = data.substring(BLOB_PREFIX_V2.length()).split(":", 4);
if (parts.length < 4) {
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
}
return new ParsedBlob(parts[0], parts[1], parts[2], parts[3]);
}
if (data.startsWith(BLOB_PREFIX_V1)) {
// Legacy v1: kms:<keyId>:<base64>. No nonce, no context binding.
// Decrypts only when caller supplies empty/null context (fingerprint "").
String[] parts = data.substring(BLOB_PREFIX_V1.length()).split(":", 2);
if (parts.length == 2) {
return new ParsedBlob(parts[0], "", "", parts[1]);
}
}
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
}
/**
* Stable fingerprint of an EncryptionContext map. AWS treats EncryptionContext as a
* case-sensitive exact match, so we hash a length-prefixed serialization of the sorted
* (key, value) pairs. Returns "" for null / empty, so omitted-context and empty-map
* ciphertexts are interchangeable (matches AWS).
*/
private static String contextFingerprint(Map<String, String> ctx) {
if (ctx == null || ctx.isEmpty()) {
return "";
}
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
new TreeMap<>(ctx).forEach((k, v) -> {
byte[] kb = k.getBytes(StandardCharsets.UTF_8);
byte[] vb = (v == null ? "" : v).getBytes(StandardCharsets.UTF_8);
md.update(ByteBuffer.allocate(4).putInt(kb.length).array());
md.update(kb);
md.update(ByteBuffer.allocate(4).putInt(vb.length).array());
md.update(vb);
});
return HexFormat.of().formatHex(md.digest());
} catch (NoSuchAlgorithmException e) {
throw new AwsException("InternalFailure", "SHA-256 unavailable", 500);
}
return null;
}
public byte[] sign(String keyId, byte[] message, String algorithm, String region) {
@@ -452,14 +543,19 @@ public class KmsService {
}
public Map<String, Object> generateDataKey(String keyId, String keySpec, int numberOfBytes, String region) {
return generateDataKey(keyId, keySpec, numberOfBytes, Map.of(), region);
}
public Map<String, Object> generateDataKey(String keyId, String keySpec, int numberOfBytes,
Map<String, String> encryptionContext, String region) {
resolveKey(keyId, region);
int len = (keySpec != null && keySpec.contains("256")) ? 32 : (numberOfBytes > 0 ? numberOfBytes : 32);
byte[] plaintext = new byte[len];
ThreadLocalRandom.current().nextBytes(plaintext);
byte[] ciphertext = encrypt(keyId, plaintext, region);
byte[] ciphertext = encrypt(keyId, plaintext, encryptionContext, region);
Map<String, Object> result = new HashMap<>();
result.put("Plaintext", plaintext);
result.put("CiphertextBlob", ciphertext);