mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
fix(kms): implement real asymmetric sign/verify and GetPublicKey (#355)
* fix(kms): implement real asymmetric sign/verify and GetPublicKey * fix(kms): implement real asymmetric sign/verify and GetPublicKey
This commit is contained in:
1 parent
788ccc8404
commit
101d45e2b0
5 files changed
+305
-24
No files matched your search
@@ -31,6 +31,7 @@ public class KmsJsonHandler {
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
return switch (action) {
|
||||
case "CreateKey" -> handleCreateKey(request, region);
|
||||
case "GetPublicKey" -> handleGetPublicKey(request, region);
|
||||
case "DescribeKey" -> handleDescribeKey(request, region);
|
||||
case "ListKeys" -> handleListKeys(request, region);
|
||||
case "Encrypt" -> handleEncrypt(request, region);
|
||||
@@ -61,15 +62,55 @@ public class KmsJsonHandler {
|
||||
|
||||
private Response handleCreateKey(JsonNode request, String region) {
|
||||
String description = request.path("Description").asText(null);
|
||||
String keyUsage = request.path("KeyUsage").asText("ENCRYPT_DECRYPT");
|
||||
String customerMasterKeySpec = !request.path("KeySpec").isMissingNode()
|
||||
? request.path("KeySpec").asText("SYMMETRIC_DEFAULT")
|
||||
: request.path("CustomerMasterKeySpec").asText("SYMMETRIC_DEFAULT");
|
||||
String policy = request.path("Policy").isMissingNode() ? null : request.path("Policy").asText(null);
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
request.path("Tags").forEach(t -> tags.put(t.path("TagKey").asText(), t.path("TagValue").asText()));
|
||||
KmsKey key = service.createKey(description, policy, tags, region);
|
||||
|
||||
KmsKey key = service.createKey(description, keyUsage, customerMasterKeySpec, policy, tags, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("KeyMetadata", keyToNode(key));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGetPublicKey(JsonNode request, String region) {
|
||||
String keyId = request.path("KeyId").asText();
|
||||
KmsKey key = service.getPublicKey(keyId, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("KeyId", key.getArn());
|
||||
response.put("PublicKey", key.getPublicKeyEncoded());
|
||||
response.put("CustomerMasterKeySpec", key.getCustomerMasterKeySpec());
|
||||
response.put("KeyUsage", key.getKeyUsage());
|
||||
|
||||
if ("SIGN_VERIFY".equals(key.getKeyUsage())) {
|
||||
ArrayNode algs = response.putArray("SigningAlgorithms");
|
||||
if (key.getCustomerMasterKeySpec().startsWith("RSA")) {
|
||||
algs.add("RSASSA_PSS_SHA_256");
|
||||
algs.add("RSASSA_PSS_SHA_384");
|
||||
algs.add("RSASSA_PSS_SHA_512");
|
||||
algs.add("RSASSA_PKCS1_V1_5_SHA_256");
|
||||
algs.add("RSASSA_PKCS1_V1_5_SHA_384");
|
||||
algs.add("RSASSA_PKCS1_V1_5_SHA_512");
|
||||
} else {
|
||||
algs.add("ECDSA_SHA_256");
|
||||
algs.add("ECDSA_SHA_384");
|
||||
algs.add("ECDSA_SHA_512");
|
||||
}
|
||||
} else {
|
||||
ArrayNode algs = response.putArray("EncryptionAlgorithms");
|
||||
if (key.getCustomerMasterKeySpec().startsWith("RSA")) {
|
||||
algs.add("RSAES_OAEP_SHA_1");
|
||||
algs.add("RSAES_OAEP_SHA_256");
|
||||
}
|
||||
}
|
||||
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeKey(JsonNode request, String region) {
|
||||
String keyId = request.path("KeyId").asText();
|
||||
KmsKey key = service.describeKey(keyId, region);
|
||||
@@ -163,8 +204,9 @@ public class KmsJsonHandler {
|
||||
String keyId = request.path("KeyId").asText();
|
||||
byte[] message = Base64.getDecoder().decode(request.path("Message").asText());
|
||||
String algorithm = request.path("SigningAlgorithm").asText("RSASSA_PSS_SHA_256");
|
||||
String messageType = request.path("MessageType").asText("RAW");
|
||||
|
||||
byte[] signature = service.sign(keyId, message, algorithm, region);
|
||||
byte[] signature = service.sign(keyId, message, algorithm, messageType, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("KeyId", service.describeKey(keyId, region).getArn());
|
||||
@@ -178,8 +220,9 @@ public class KmsJsonHandler {
|
||||
byte[] message = Base64.getDecoder().decode(request.path("Message").asText());
|
||||
byte[] signature = Base64.getDecoder().decode(request.path("Signature").asText());
|
||||
String algorithm = request.path("SigningAlgorithm").asText("RSASSA_PSS_SHA_256");
|
||||
String messageType = request.path("MessageType").asText("RAW");
|
||||
|
||||
boolean valid = service.verify(keyId, message, signature, algorithm, region);
|
||||
boolean valid = service.verify(keyId, message, signature, algorithm, messageType, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("KeyId", service.describeKey(keyId, region).getArn());
|
||||
@@ -306,6 +349,7 @@ public class KmsJsonHandler {
|
||||
node.put("Origin", "AWS_KMS");
|
||||
node.put("KeyManager", "CUSTOMER");
|
||||
node.put("CustomerMasterKeySpec", k.getCustomerMasterKeySpec());
|
||||
node.put("KeySpec", k.getCustomerMasterKeySpec());
|
||||
if (k.getDeletionDate() > 0) {
|
||||
node.put("DeletionDate", k.getDeletionDate());
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.*;
|
||||
import java.security.spec.*;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
@@ -48,10 +50,14 @@ public class KmsService {
|
||||
"\"Action\":\"kms:*\",\"Resource\":\"*\"}]}";
|
||||
|
||||
public KmsKey createKey(String description, String region) {
|
||||
return createKey(description, null, Map.of(), region);
|
||||
return createKey(description, "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", null, Map.of(), region);
|
||||
}
|
||||
|
||||
public KmsKey createKey(String description, String policy, Map<String, String> tags, String region) {
|
||||
return createKey(description, "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", policy, tags, region);
|
||||
}
|
||||
|
||||
public KmsKey createKey(String description, String keyUsage, String customerMasterKeySpec, String policy, Map<String, String> tags, String region) {
|
||||
String keyId = UUID.randomUUID().toString();
|
||||
String arn = regionResolver.buildArn("kms", region, "key/" + keyId);
|
||||
|
||||
@@ -59,13 +65,59 @@ public class KmsService {
|
||||
key.setKeyId(keyId);
|
||||
key.setArn(arn);
|
||||
key.setDescription(description);
|
||||
key.setKeyUsage(keyUsage != null ? keyUsage : "ENCRYPT_DECRYPT");
|
||||
key.setCustomerMasterKeySpec(customerMasterKeySpec != null ? customerMasterKeySpec : "SYMMETRIC_DEFAULT");
|
||||
key.setPolicy(policy != null ? policy : DEFAULT_KEY_POLICY);
|
||||
if (tags != null) {
|
||||
key.getTags().putAll(tags);
|
||||
}
|
||||
|
||||
generateKeyMaterial(key);
|
||||
|
||||
keyStore.put(region + "::" + keyId, key);
|
||||
LOG.infov("Created KMS key: {0} in {1}", keyId, region);
|
||||
LOG.infov("Created KMS key: {0} ({1}/{2}) in {3}", keyId, key.getKeyUsage(), key.getCustomerMasterKeySpec(), region);
|
||||
return key;
|
||||
}
|
||||
|
||||
private void generateKeyMaterial(KmsKey key) {
|
||||
String spec = key.getCustomerMasterKeySpec();
|
||||
if ("SYMMETRIC_DEFAULT".equals(spec)) {
|
||||
return; // Use existing mock behavior for symmetric keys
|
||||
}
|
||||
|
||||
try {
|
||||
KeyPairGenerator generator;
|
||||
if (spec.startsWith("RSA_")) {
|
||||
generator = KeyPairGenerator.getInstance("RSA");
|
||||
int size = Integer.parseInt(spec.substring(4));
|
||||
generator.initialize(size);
|
||||
} else if (spec.startsWith("ECC_")) {
|
||||
generator = KeyPairGenerator.getInstance("EC");
|
||||
String curveName = switch (spec) {
|
||||
case "ECC_NIST_P256" -> "secp256r1";
|
||||
case "ECC_NIST_P384" -> "secp384r1";
|
||||
case "ECC_NIST_P521" -> "secp521r1";
|
||||
case "ECC_SECG_P256K1" -> "secp256k1";
|
||||
default -> throw new AwsException("InvalidCustomerMasterKeySpecException", "Unsupported curve: " + spec, 400);
|
||||
};
|
||||
generator.initialize(new ECGenParameterSpec(curveName));
|
||||
} else {
|
||||
throw new AwsException("InvalidCustomerMasterKeySpecException", "Unsupported key spec: " + spec, 400);
|
||||
}
|
||||
|
||||
KeyPair pair = generator.generateKeyPair();
|
||||
key.setPrivateKeyEncoded(Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));
|
||||
key.setPublicKeyEncoded(Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()));
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InternalFailure", "Failed to generate key material: " + e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
public KmsKey getPublicKey(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
if ("SYMMETRIC_DEFAULT".equals(key.getCustomerMasterKeySpec())) {
|
||||
throw new AwsException("UnsupportedOperationException", "GetPublicKey is not supported for symmetric keys.", 400);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
@@ -198,17 +250,86 @@ public class KmsService {
|
||||
}
|
||||
|
||||
public byte[] sign(String keyId, byte[] message, String algorithm, String region) {
|
||||
resolveKey(keyId, region);
|
||||
// Local mock signature: "sig:keyId:algo:base64(message)"
|
||||
String sig = "sig:" + keyId + ":" + algorithm + ":" + Base64.getEncoder().encodeToString(message);
|
||||
return sig.getBytes(StandardCharsets.UTF_8);
|
||||
return sign(keyId, message, algorithm, "RAW", region);
|
||||
}
|
||||
|
||||
public byte[] sign(String keyId, byte[] message, String algorithm, String messageType, String region) {
|
||||
KmsKey kmsKey = resolveKey(keyId, region);
|
||||
if ("SYMMETRIC_DEFAULT".equals(kmsKey.getCustomerMasterKeySpec())) {
|
||||
throw new AwsException("UnsupportedOperationException", "Unsupported key spec for signing.", 400);
|
||||
}
|
||||
|
||||
try {
|
||||
PrivateKey privateKey = loadPrivateKey(kmsKey.getPrivateKeyEncoded(), kmsKey.getCustomerMasterKeySpec());
|
||||
String jcaAlgo = mapAlgorithm(algorithm);
|
||||
|
||||
if ("DIGEST".equals(messageType)) {
|
||||
// If message is already a digest, we need a "NONEwith..." algorithm
|
||||
jcaAlgo = "NONEwith" + (kmsKey.getCustomerMasterKeySpec().startsWith("RSA") ? "RSA" : "ECDSA");
|
||||
}
|
||||
|
||||
Signature sig = Signature.getInstance(jcaAlgo);
|
||||
sig.initSign(privateKey);
|
||||
sig.update(message);
|
||||
return sig.sign();
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InternalFailure", "Failed to sign message: " + e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean verify(String keyId, byte[] message, byte[] signature, String algorithm, String region) {
|
||||
resolveKey(keyId, region);
|
||||
String actualSig = new String(signature, StandardCharsets.UTF_8);
|
||||
String expectedSig = "sig:" + keyId + ":" + algorithm + ":" + Base64.getEncoder().encodeToString(message);
|
||||
return actualSig.equals(expectedSig);
|
||||
return verify(keyId, message, signature, algorithm, "RAW", region);
|
||||
}
|
||||
|
||||
public boolean verify(String keyId, byte[] message, byte[] signature, String algorithm, String messageType, String region) {
|
||||
KmsKey kmsKey = resolveKey(keyId, region);
|
||||
if ("SYMMETRIC_DEFAULT".equals(kmsKey.getCustomerMasterKeySpec())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
PublicKey publicKey = loadPublicKey(kmsKey.getPublicKeyEncoded(), kmsKey.getCustomerMasterKeySpec());
|
||||
String jcaAlgo = mapAlgorithm(algorithm);
|
||||
|
||||
if ("DIGEST".equals(messageType)) {
|
||||
jcaAlgo = "NONEwith" + (kmsKey.getCustomerMasterKeySpec().startsWith("RSA") ? "RSA" : "ECDSA");
|
||||
}
|
||||
|
||||
Signature sig = Signature.getInstance(jcaAlgo);
|
||||
sig.initVerify(publicKey);
|
||||
sig.update(message);
|
||||
return sig.verify(signature);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Verification failed for key {0}: {1}", keyId, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private PrivateKey loadPrivateKey(String encoded, String spec) throws Exception {
|
||||
byte[] decoded = Base64.getDecoder().decode(encoded);
|
||||
KeyFactory factory = KeyFactory.getInstance(spec.startsWith("RSA") ? "RSA" : "EC");
|
||||
return factory.generatePrivate(new PKCS8EncodedKeySpec(decoded));
|
||||
}
|
||||
|
||||
private PublicKey loadPublicKey(String encoded, String spec) throws Exception {
|
||||
byte[] decoded = Base64.getDecoder().decode(encoded);
|
||||
KeyFactory factory = KeyFactory.getInstance(spec.startsWith("RSA") ? "RSA" : "EC");
|
||||
return factory.generatePublic(new X509EncodedKeySpec(decoded));
|
||||
}
|
||||
|
||||
private String mapAlgorithm(String awsAlgo) {
|
||||
return switch (awsAlgo) {
|
||||
case "ECDSA_SHA_256" -> "SHA256withECDSA";
|
||||
case "ECDSA_SHA_384" -> "SHA384withECDSA";
|
||||
case "ECDSA_SHA_512" -> "SHA512withECDSA";
|
||||
case "RSASSA_PSS_SHA_256" -> "SHA256withRSA/PSS";
|
||||
case "RSASSA_PSS_SHA_384" -> "SHA384withRSA/PSS";
|
||||
case "RSASSA_PSS_SHA_512" -> "SHA512withRSA/PSS";
|
||||
case "RSASSA_PKCS1_V1_5_SHA_256" -> "SHA256withRSA";
|
||||
case "RSASSA_PKCS1_V1_5_SHA_384" -> "SHA384withRSA";
|
||||
case "RSASSA_PKCS1_V1_5_SHA_512" -> "SHA512withRSA";
|
||||
default -> throw new AwsException("InvalidSigningAlgorithmException", "Unsupported algorithm: " + awsAlgo, 400);
|
||||
};
|
||||
}
|
||||
|
||||
public Map<String, Object> generateDataKey(String keyId, String keySpec, int numberOfBytes, String region) {
|
||||
|
||||
@@ -22,6 +22,8 @@ public class KmsKey {
|
||||
private String policy;
|
||||
private boolean keyRotationEnabled = false;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
private String privateKeyEncoded;
|
||||
private String publicKeyEncoded;
|
||||
|
||||
public KmsKey() {
|
||||
this.creationDate = Instant.now().getEpochSecond();
|
||||
@@ -62,4 +64,10 @@ public class KmsKey {
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
|
||||
public String getPrivateKeyEncoded() { return privateKeyEncoded; }
|
||||
public void setPrivateKeyEncoded(String privateKeyEncoded) { this.privateKeyEncoded = privateKeyEncoded; }
|
||||
|
||||
public String getPublicKeyEncoded() { return publicKeyEncoded; }
|
||||
public void setPublicKeyEncoded(String publicKeyEncoded) { this.publicKeyEncoded = publicKeyEncoded; }
|
||||
}
|
||||
Reference in new issue
Block a user