diff --git a/compatibility-tests/sdk-test-python/tests/test_acm.py b/compatibility-tests/sdk-test-python/tests/test_acm.py index ea16775883..f974b60a4e 100644 --- a/compatibility-tests/sdk-test-python/tests/test_acm.py +++ b/compatibility-tests/sdk-test-python/tests/test_acm.py @@ -7,7 +7,7 @@ import pytest from botocore.exceptions import ClientError from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa from cryptography.x509.oid import NameOID FAKE_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/00000000-0000-0000-0000-000000000000" @@ -27,6 +27,38 @@ class TestACMCertificateLifecycle: finally: acm_client.delete_certificate(CertificateArn=arn) + @pytest.mark.parametrize( + "key_algorithm,key_type", + [("RSA_2048", rsa.RSAPublicKey), ("EC_prime256v1", ec.EllipticCurvePublicKey)], + ) + def test_request_certificate_key_algorithms( + self, acm_client, key_algorithm, key_type + ): + """Test RequestCertificate issues a parseable certificate for each key algorithm.""" + response = acm_client.request_certificate( + DomainName=f"{key_algorithm.lower().replace('_', '-')}.example.com", + KeyAlgorithm=key_algorithm, + ) + arn = response["CertificateArn"] + + try: + pem = acm_client.get_certificate(CertificateArn=arn)["Certificate"] + certificate = x509.load_pem_x509_certificate(pem.encode()) + assert isinstance(certificate.public_key(), key_type) + # A certificate whose signature does not match its own contents would + # still parse, so check the self-signature rather than trusting the PEM. + certificate.public_key().verify( + certificate.signature, + certificate.tbs_certificate_bytes, + *( + (ec.ECDSA(certificate.signature_hash_algorithm),) + if isinstance(certificate.public_key(), ec.EllipticCurvePublicKey) + else (padding.PKCS1v15(), certificate.signature_hash_algorithm) + ), + ) + finally: + acm_client.delete_certificate(CertificateArn=arn) + def test_describe_certificate(self, acm_client): """Test DescribeCertificate returns certificate details.""" response = acm_client.request_certificate(DomainName="describe.example.com") @@ -164,8 +196,9 @@ class TestACMImportExport: acm_client.delete_certificate(CertificateArn=arn) def test_export_certificate(self, acm_client): - """Test ExportCertificate on imported cert returns cert and key.""" + """Test ExportCertificate returns the imported key, encrypted under the passphrase.""" cert_pem, key_pem = self._generate_self_signed_cert() + passphrase = b"test-passphrase" import_response = acm_client.import_certificate( Certificate=cert_pem, PrivateKey=key_pem @@ -174,10 +207,27 @@ class TestACMImportExport: try: response = acm_client.export_certificate( - CertificateArn=arn, Passphrase=b"test-passphrase" + CertificateArn=arn, Passphrase=passphrase ) assert response["Certificate"] assert response["PrivateKey"] + + # Asserting on the PEM header alone would pass for a key no client can + # open. Decrypt it with the passphrase and check it is the key that was + # imported, which is the whole point of the export. + exported_key = serialization.load_pem_private_key( + response["PrivateKey"].encode(), password=passphrase + ) + imported_key = serialization.load_pem_private_key(key_pem, password=None) + assert ( + exported_key.private_numbers() == imported_key.private_numbers() + ) + + # The passphrase has to actually be doing the work. + with pytest.raises(ValueError): + serialization.load_pem_private_key( + response["PrivateKey"].encode(), password=b"wrong-passphrase" + ) finally: acm_client.delete_certificate(CertificateArn=arn) diff --git a/compatibility-tests/sdk-test-python/tests/test_kms.py b/compatibility-tests/sdk-test-python/tests/test_kms.py index 632136f12c..9ebc02f103 100644 --- a/compatibility-tests/sdk-test-python/tests/test_kms.py +++ b/compatibility-tests/sdk-test-python/tests/test_kms.py @@ -2,9 +2,38 @@ import hashlib +import boto3 import pytest from botocore.exceptions import ClientError -from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, padding + + +# Every signing algorithm each key spec declares. RSA key generation is the only +# real cost here and the fixture below creates one key per spec, so covering the +# full matrix is cheaper than the per-case keys it replaced. +RSA_SIGNING_ALGORITHMS = [ + ("RSASSA_PSS_SHA_256", hashes.SHA256), + ("RSASSA_PSS_SHA_384", hashes.SHA384), + ("RSASSA_PSS_SHA_512", hashes.SHA512), + ("RSASSA_PKCS1_V1_5_SHA_256", hashes.SHA256), + ("RSASSA_PKCS1_V1_5_SHA_384", hashes.SHA384), + ("RSASSA_PKCS1_V1_5_SHA_512", hashes.SHA512), +] + +SIGNING_CASES = [ + (key_spec, algorithm, digest) + for key_spec in ("RSA_2048", "RSA_3072", "RSA_4096") + for algorithm, digest in RSA_SIGNING_ALGORITHMS +] + [ + ("ECC_NIST_P256", "ECDSA_SHA_256", hashes.SHA256), + ("ECC_NIST_P384", "ECDSA_SHA_384", hashes.SHA384), + ("ECC_NIST_P521", "ECDSA_SHA_512", hashes.SHA512), + # secp256k1 is signed with BouncyCastle's lightweight signer, reached directly + # rather than through a JCA provider, and the JDK dropped the curve. It is the + # crypto path most likely to break in a native image. + ("ECC_SECG_P256K1", "ECDSA_SHA_256", hashes.SHA256), +] class TestKMSKey: @@ -207,37 +236,73 @@ class TestKMSEncryption: class TestKMSSigning: """Test KMS signing operations.""" - def test_sign_and_verify(self, kms_client): - """Test Sign and Verify with RSA key.""" - # Create an asymmetric signing key - response = kms_client.create_key( - Description="pytest-signing-key", - KeyUsage="SIGN_VERIFY", - KeySpec="RSA_2048", - ) - key_id = response["KeyMetadata"]["KeyId"] + @pytest.fixture(scope="class") + @staticmethod + def signing_key(aws_config, client_config): + """Return one signing key per key spec, created on first use. + + RSA key generation dominates the runtime of this class, so the key is + shared across every algorithm tested against it. + """ + client = boto3.client("kms", config=client_config, **aws_config) + created = {} + + def key_for(key_spec): + if key_spec not in created: + created[key_spec] = client.create_key( + Description="pytest-signing-key", + KeyUsage="SIGN_VERIFY", + KeySpec=key_spec, + )["KeyMetadata"]["KeyId"] + return created[key_spec] + + yield key_for + for key_id in created.values(): + client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7) + + @pytest.mark.parametrize("key_spec,signing_algorithm,digest", SIGNING_CASES) + def test_sign_and_verify( + self, kms_client, signing_key, key_spec, signing_algorithm, digest + ): + """Test Sign and Verify, and check the signature against an outside library.""" + key_id = signing_key(key_spec) message = b"message to sign" - try: - # Sign the message - sign_response = kms_client.sign( - KeyId=key_id, - Message=message, - SigningAlgorithm="RSASSA_PSS_SHA_256", - ) - signature = sign_response["Signature"] - assert signature + # Sign the message + sign_response = kms_client.sign( + KeyId=key_id, + Message=message, + SigningAlgorithm=signing_algorithm, + ) + signature = sign_response["Signature"] + assert signature - # Verify the signature - verify_response = kms_client.verify( - KeyId=key_id, - Message=message, - Signature=signature, - SigningAlgorithm="RSASSA_PSS_SHA_256", - ) - assert verify_response["SignatureValid"] - finally: - kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7) + # Verify the signature + verify_response = kms_client.verify( + KeyId=key_id, + Message=message, + Signature=signature, + SigningAlgorithm=signing_algorithm, + ) + assert verify_response["SignatureValid"] + + # Sign and Verify are both Floci, so agreeing with each other proves + # nothing about the padding, the mask generation function or the salt + # length. Check the signature against GetPublicKey with the parameters + # AWS documents for this algorithm instead. + public_key = serialization.load_der_public_key( + kms_client.get_public_key(KeyId=key_id)["PublicKey"] + ) + if signing_algorithm.startswith("ECDSA"): + public_key.verify(signature, message, ec.ECDSA(digest())) + else: + if signing_algorithm.startswith("RSASSA_PSS"): + scheme = padding.PSS( + mgf=padding.MGF1(digest()), salt_length=digest.digest_size + ) + else: + scheme = padding.PKCS1v15() + public_key.verify(signature, message, scheme, digest()) def test_ed25519_sign_and_verify(self, kms_client): diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java index 69de131696..f8dd8e6161 100644 --- a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java +++ b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java @@ -3,7 +3,6 @@ package io.github.hectorvent.floci.config; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.services.acm.CertificateGenerator; import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; -import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.eclipse.microprofile.config.spi.ConfigSource; import org.jboss.logging.Logger; @@ -19,7 +18,6 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; -import java.security.Security; /** * A MicroProfile {@link ConfigSource} that dynamically provides Quarkus TLS/SSL @@ -65,13 +63,6 @@ public class TlsConfigSource implements ConfigSource { return; } - // BouncyCastle may not be registered yet — this ConfigSource runs before CDI (@Startup beans) - // and before quarkus-security's runtime provider registration. Register it up front so BOTH - // certificate parsing (isSelfSigned/parseCertificate) and generation work; otherwise - // parseCertificate fails "no such provider: BC", isSelfSigned returns false, and the persisted - // self-signed certificate is needlessly regenerated on every restart. - ensureBouncyCastleRegistered(); - String certPath = resolveProperty("floci.tls.cert-path", ""); String keyPath = resolveProperty("floci.tls.key-path", ""); String selfSigned = resolveProperty("floci.tls.self-signed", "true"); @@ -171,16 +162,9 @@ public class TlsConfigSource implements ConfigSource { return defaultValue; } - private static void ensureBouncyCastleRegistered() { - if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { - Security.addProvider(new BouncyCastleProvider()); - } - } - private void generateSelfSignedCert(Path tlsDir, Path certFile, Path keyFile) { try { Files.createDirectories(tlsDir); - ensureBouncyCastleRegistered(); // Extract custom hostnames and combine with defaults List customHostnames = extractCustomHostnames(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/BouncyCastleInitializer.java b/src/main/java/io/github/hectorvent/floci/core/common/BouncyCastleInitializer.java deleted file mode 100644 index c0cc076c7c..0000000000 --- a/src/main/java/io/github/hectorvent/floci/core/common/BouncyCastleInitializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.hectorvent.floci.core.common; - -import io.quarkus.runtime.Startup; -import jakarta.enterprise.context.ApplicationScoped; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.jboss.logging.Logger; - -import java.security.Security; - -/** - * Ensures BouncyCastle security provider is registered. - * With quarkus-security extension and quarkus.security.security-providers=BC, - * this is handled by Quarkus. - */ -@ApplicationScoped -@Startup -public class BouncyCastleInitializer { - - private static final Logger LOG = Logger.getLogger(BouncyCastleInitializer.class); - - static { - if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { - Security.addProvider(new BouncyCastleProvider()); - LOG.debug("Registered BouncyCastle security provider (manual fallback)"); - } else { - LOG.debug("BouncyCastle provider already registered by Quarkus"); - } - } - - public BouncyCastleInitializer() { - } -} diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java index 7fd314ddd2..f75351a049 100644 --- a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java +++ b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java @@ -2,8 +2,10 @@ package io.github.hectorvent.floci.services.acm; import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; import jakarta.enterprise.context.ApplicationScoped; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo; import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.GeneralName; @@ -13,7 +15,6 @@ import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; -import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; @@ -21,12 +22,13 @@ import org.bouncycastle.openssl.jcajce.JcePEMEncryptorBuilder; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo; -import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfoBuilder; -import org.bouncycastle.pkcs.jcajce.JcaPKCS8EncryptedPrivateKeyInfoBuilder; -import org.bouncycastle.pkcs.jcajce.JcePKCSPBEOutputEncryptorBuilder; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.jboss.logging.Logger; +import javax.crypto.Cipher; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.PBEParameterSpec; import java.io.StringReader; import java.io.StringWriter; import java.math.BigInteger; @@ -52,6 +54,9 @@ public class CertificateGenerator { private static final Logger LOG = Logger.getLogger(CertificateGenerator.class); private static final String ISSUER_DN = "CN=Amazon,OU=Server CA 1B,O=Amazon,C=US"; private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + private static final String PBE_ALGORITHM = "PBEWithHmacSHA256AndAES_256"; + private static final int PBE_SALT_BYTES = 16; + private static final int PBE_ITERATIONS = 4096; /** * Pattern matching IPv4 addresses (e.g. 192.168.1.100) and IPv6 addresses @@ -166,12 +171,10 @@ public class CertificateGenerator { // a cosmetic Amazon DN (mimicking ACM); for generateSelfSignedCertificate() issuer == // subject, so the cert is a valid self-signed trust anchor. ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm) - .setProvider(BouncyCastleProvider.PROVIDER_NAME) .build(keyPair.getPrivate()); X509CertificateHolder certHolder = certBuilder.build(signer); X509Certificate cert = new JcaX509CertificateConverter() - .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certHolder); String certPem = toPem(cert); @@ -197,10 +200,10 @@ public class CertificateGenerator { private KeyPair generateKeyPair(KeyAlgorithm keyAlgorithm) throws Exception { KeyPairGenerator keyGen; if ("EC".equals(keyAlgorithm.getAlgorithm())) { - keyGen = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME); + keyGen = KeyPairGenerator.getInstance("EC"); keyGen.initialize(new ECGenParameterSpec(keyAlgorithm.getCurveName()), SECURE_RANDOM); } else { - keyGen = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); + keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(keyAlgorithm.getKeySize(), SECURE_RANDOM); } return keyGen.generateKeyPair(); @@ -260,16 +263,24 @@ public class CertificateGenerator { try { PrivateKey privateKey = parsePrivateKey(privateKeyPem); - // Use AES-256-CBC instead of deprecated Triple-DES - JcePKCSPBEOutputEncryptorBuilder encryptorBuilder = new JcePKCSPBEOutputEncryptorBuilder( - NISTObjectIdentifiers.id_aes256_CBC - ); - encryptorBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME); + // PBES2 with AES-256-CBC, run through the JDK so no JCE provider has to be + // registered. The algorithm name fixes the PBKDF2 PRF to HMAC-SHA256, and the + // salt and iteration count are passed explicitly so the output does not depend + // on provider defaults. The ASN.1 below only wraps the result, so it needs no + // provider either. + var secretKey = SecretKeyFactory.getInstance(PBE_ALGORITHM) + .generateSecret(new PBEKeySpec(passphrase.toCharArray())); + var salt = new byte[PBE_SALT_BYTES]; + SECURE_RANDOM.nextBytes(salt); + var cipher = Cipher.getInstance(PBE_ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, secretKey, new PBEParameterSpec(salt, PBE_ITERATIONS)); + var ciphertext = cipher.doFinal(privateKey.getEncoded()); - PKCS8EncryptedPrivateKeyInfoBuilder pkcs8Builder = new JcaPKCS8EncryptedPrivateKeyInfoBuilder(privateKey); - PKCS8EncryptedPrivateKeyInfo encryptedInfo = pkcs8Builder.build( - encryptorBuilder.build(passphrase.toCharArray()) - ); + var scheme = new AlgorithmIdentifier( + PKCSObjectIdentifiers.id_PBES2, + ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())); + var encryptedInfo = + new PKCS8EncryptedPrivateKeyInfo(new EncryptedPrivateKeyInfo(scheme, ciphertext)); StringWriter sw = new StringWriter(); try (JcaPEMWriter pemWriter = new JcaPEMWriter(sw)) { @@ -288,7 +299,6 @@ public class CertificateGenerator { Object obj = parser.readObject(); if (obj instanceof X509CertificateHolder holder) { return new JcaX509CertificateConverter() - .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(holder); } throw new IllegalArgumentException("Invalid certificate PEM format"); @@ -301,8 +311,7 @@ public class CertificateGenerator { public PrivateKey parsePrivateKey(String keyPem) { try (PEMParser parser = new PEMParser(new StringReader(keyPem))) { Object obj = parser.readObject(); - JcaPEMKeyConverter converter = new JcaPEMKeyConverter() - .setProvider(BouncyCastleProvider.PROVIDER_NAME); + JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); if (obj instanceof org.bouncycastle.openssl.PEMKeyPair pemKeyPair) { return converter.getKeyPair(pemKeyPair).getPrivate(); 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 fd3e760ce0..28416443e1 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 @@ -29,6 +29,11 @@ import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.DigestInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.digests.SHA384Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; +import org.bouncycastle.crypto.engines.RSABlindedEngine; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters; import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; @@ -37,6 +42,9 @@ import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.signers.ECDSASigner; import org.bouncycastle.crypto.signers.Ed25519phSigner; +import org.bouncycastle.crypto.signers.PSSSigner; +import org.bouncycastle.crypto.util.PrivateKeyFactory; +import org.bouncycastle.crypto.util.PublicKeyFactory; import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey; import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey; import org.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi; @@ -56,7 +64,9 @@ import java.nio.charset.StandardCharsets; import java.security.*; import java.security.interfaces.EdECPrivateKey; import java.security.spec.ECGenParameterSpec; +import java.security.spec.MGF1ParameterSpec; import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.PSSParameterSpec; import java.security.spec.X509EncodedKeySpec; import java.time.Instant; import java.util.*; @@ -948,6 +958,9 @@ public class KmsService implements ResourceProvider { if (ed25519) { return signEd25519(privateKey, message, algorithm); } + if (messageType == DIGEST && isRsaPssRequest(kmsKey.getKeySpec(), algorithm)) { + return signRsaPssDigest(privateKey, message, algorithm); + } String jcaAlgo = switch (messageType) { // If message is already a digest, we need a "NONEwith..." algorithm case DIGEST -> "NONEwith" + (kmsKey.getKeySpec().getKeyType() == KmsKeySpec.KeyType.RSA ? "RSA" : "ECDSA"); @@ -962,10 +975,12 @@ public class KmsService implements ResourceProvider { if (isSecgP256k1(kmsKey.getKeySpec())) { return signSecgP256k1(privateKey, message, jcaAlgo); } - Signature sig = Signature.getInstance(jcaAlgo); + var sig = signatureFor(jcaAlgo); sig.initSign(privateKey); sig.update(message); return sig.sign(); + } catch (AwsException e) { + throw e; } catch (Exception e) { throw new AwsException("InternalFailure", "Failed to sign message: " + e.getMessage(), 500); } @@ -994,6 +1009,9 @@ public class KmsService implements ResourceProvider { String jcaAlgo = KmsKeySpec.getSignVerifyAlgorithm(algorithm).getJavaName(); if (DIGEST.equals(messageType)) { + if (isRsaPssRequest(kmsKey.getKeySpec(), algorithm)) { + return verifyRsaPssDigest(publicKey, message, signature, algorithm); + } jcaAlgo = "NONEwith" + (kmsKey.getKeySpec().getKeyType() == KmsKeySpec.KeyType.RSA ? "RSA" : "ECDSA"); if (isPKCS1v1_5(kmsKey.getKeySpec().getAlgorithm().getFirst())) { // Mirror sign(): verify against DigestInfo{hashOID, digest} (RFC 8017 9.2). @@ -1003,10 +1021,12 @@ public class KmsService implements ResourceProvider { if (isSecgP256k1(kmsKey.getKeySpec())) { return verifySecgP256k1(publicKey, message, signature, jcaAlgo); } - Signature sig = Signature.getInstance(jcaAlgo); + var sig = signatureFor(jcaAlgo); sig.initVerify(publicKey); sig.update(message); return sig.verify(signature); + } catch (AwsException e) { + throw e; } catch (Exception e) { LOG.warnv("Verification failed for key {0}: {1}", keyId, e.getMessage()); return false; @@ -1265,6 +1285,71 @@ public class KmsService implements ResourceProvider { return SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()).getPublicKeyData().getBytes(); } + /** + * Builds the {@link Signature} for a KMS signing algorithm. + * + *

BouncyCastle names PSS signatures {@code SHAnnnwithRSA/PSS}, and only its provider + * answers to that name. The JDK exposes one {@code RSASSA-PSS} Signature whose digest, + * mask generation function and salt length come from a parameter spec instead. AWS KMS + * RSASSA_PSS_SHA_nnn uses MGF1 over the same digest with a salt as long as that digest, + * which is what BouncyCastle's alias defaults to, so a signature made either way verifies + * against the other. Every other name Floci asks for is a standard JCA name. + */ + private static Signature signatureFor(String jcaAlgorithm) throws GeneralSecurityException { + if (!jcaAlgorithm.endsWith("withRSA/PSS")) { + return Signature.getInstance(jcaAlgorithm); + } + var digest = "SHA-" + jcaAlgorithm.substring("SHA".length(), jcaAlgorithm.indexOf("with")); + var maskGeneration = switch (digest) { + case "SHA-256" -> MGF1ParameterSpec.SHA256; + case "SHA-384" -> MGF1ParameterSpec.SHA384; + case "SHA-512" -> MGF1ParameterSpec.SHA512; + default -> throw new NoSuchAlgorithmException("Unsupported PSS digest: " + digest); + }; + var saltLength = MessageDigest.getInstance(digest).getDigestLength(); + var signature = Signature.getInstance("RSASSA-PSS"); + signature.setParameter(new PSSParameterSpec(digest, "MGF1", maskGeneration, saltLength, 1)); + return signature; + } + + private static boolean isRsaPssRequest(KmsKeySpec spec, String algorithm) { + return spec.getKeyType() == KmsKeySpec.KeyType.RSA && algorithm.startsWith("RSASSA_PSS"); + } + + /** + * Signs a pre-computed digest with RSASSA-PSS. + * + *

Real KMS applies the PSS encoding directly to the digest a {@code MessageType=DIGEST} + * caller sends. The JDK's {@code RSASSA-PSS} Signature always hashes its input first, so + * this uses BouncyCastle's lightweight raw PSS signer, instantiated directly like the + * secp256k1 and Ed25519ph paths. The raw signer defaults to MGF1 over the same digest with + * a salt as long as that digest, matching {@link #signatureFor(String)}, so RAW and DIGEST + * signatures verify against each other. + */ + private static byte[] signRsaPssDigest(PrivateKey privateKey, byte[] digest, String algorithm) throws Exception { + var signer = rawPssSigner(algorithm); + signer.init(true, new ParametersWithRandom(PrivateKeyFactory.createKey(privateKey.getEncoded()), SECURE_RANDOM)); + signer.update(digest, 0, digest.length); + return signer.generateSignature(); + } + + private static boolean verifyRsaPssDigest(PublicKey publicKey, byte[] digest, byte[] signature, String algorithm) throws Exception { + var signer = rawPssSigner(algorithm); + signer.init(false, PublicKeyFactory.createKey(publicKey.getEncoded())); + signer.update(digest, 0, digest.length); + return signer.verifySignature(signature); + } + + private static PSSSigner rawPssSigner(String algorithm) { + Digest digest = switch (algorithm) { + case "RSASSA_PSS_SHA_256" -> new SHA256Digest(); + case "RSASSA_PSS_SHA_384" -> new SHA384Digest(); + case "RSASSA_PSS_SHA_512" -> new SHA512Digest(); + default -> throw new AwsException("InvalidSigningAlgorithmException", "Unsupported algorithm: " + algorithm, 400); + }; + return PSSSigner.createRawSigner(new RSABlindedEngine(), digest); + } + private static boolean isPKCS1v1_5(KmsKeySpec.Algorithm spec) { return spec == KmsKeySpec.Algorithm.RSASSA_PKCS1_V1_5_SHA_256 || spec == KmsKeySpec.Algorithm.RSASSA_PKCS1_V1_5_SHA_384 diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java index c6f0bfc0f9..e17e6dc3aa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java @@ -7,7 +7,6 @@ import io.github.hectorvent.floci.services.acm.CertificateGenerator; import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; -import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.jboss.logging.Logger; import javax.net.ssl.KeyManagerFactory; @@ -21,7 +20,6 @@ import java.security.KeyPair; import java.security.KeyStore; import java.security.PrivateKey; import java.security.SecureRandom; -import java.security.Security; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -108,7 +106,6 @@ public class RdsProxyTlsCertificates { if (sslContext != null) { return; } - ensureBouncyCastleRegistered(); Path tlsDir = tlsDir(); Path certFile = tlsDir.resolve(CERT_NAME); Path keyFile = tlsDir.resolve(KEY_NAME); @@ -195,12 +192,6 @@ public class RdsProxyTlsCertificates { return Path.of(config.storage().persistentPath(), TLS_DIR); } - private static void ensureBouncyCastleRegistered() { - if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { - Security.addProvider(new BouncyCastleProvider()); - } - } - /** * Restricts {@code path} to owner-only access. This CA's private key is meant to be trusted by * a developer's client tooling (e.g. {@code sslmode=verify-full}), so unlike Floci's other diff --git a/src/main/resources/META-INF/native-image/reflect-config.json b/src/main/resources/META-INF/native-image/reflect-config.json index 6f7df66adc..e7563033db 100644 --- a/src/main/resources/META-INF/native-image/reflect-config.json +++ b/src/main/resources/META-INF/native-image/reflect-config.json @@ -2402,153 +2402,6 @@ "allDeclaredMethods": true, "allDeclaredFields": true }, - { - "name": "org.bouncycastle.jce.provider.BouncyCastleProvider", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi$EC", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyPairGeneratorSpi", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.ec.KeyPairGeneratorSpi$EC", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.digest.SHA256$Digest", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.digest.SHA384$Digest", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.rsa.DigestSignatureSpi$SHA256", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.ec.SignatureSpi$ecDSA256", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.symmetric.AES$ECB", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.symmetric.PBEPBKDF2$PBKDF2withSHA256", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.digest.SHA512$Digest", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.rsa.DigestSignatureSpi$SHA512", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.ec.SignatureSpi$ecDSA512", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.symmetric.AES$CBC", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.EC$Mappings", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.RSA$Mappings", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.asymmetric.X509$Mappings", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.digest.SHA512$Mappings", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, - { - "name": "org.bouncycastle.jcajce.provider.symmetric.AES$Mappings", - "allDeclaredConstructors": true, - "allPublicConstructors": true, - "allDeclaredMethods": true, - "allDeclaredFields": true - }, { "name": "io.github.hectorvent.floci.services.appsync.graphql.AppSyncVtlEngine", "allDeclaredConstructors": true, diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 0adb5c579a..678b649ba9 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -17,8 +17,6 @@ quarkus: max-body-size: ${floci.protocols.max-request-size}M datasource: active: false - security: - security-providers: BC shutdown: # Enables the pre-shutdown phase so stop hooks run before the HTTP server stops. # No 'delay' value is set - observers run synchronously, no artificial sleep is introduced. @@ -67,12 +65,6 @@ quarkus: - --enable-url-protocols=http,https - --initialize-at-run-time=io.vertx.ext.mail.impl.sasl.NTLMEngineImpl - --initialize-at-run-time=com.github.dockerjava.transport.NamedPipeSocket$Kernel32 - - --initialize-at-run-time=org.bouncycastle.jcajce.provider.drbg.DRBG$Default - - --initialize-at-run-time=org.bouncycastle.jcajce.provider.drbg.DRBG$NonceAndIV - - --initialize-at-run-time=org.bouncycastle.crypto.prng.SP800SecureRandom - - --initialize-at-run-time=org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyPairGeneratorSpi - - --initialize-at-run-time=org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory - - --initialize-at-run-time=io.github.hectorvent.floci.core.common.BouncyCastleInitializer - --initialize-at-run-time=io.github.hectorvent.floci.services.acm.AcmService - --initialize-at-run-time=io.github.hectorvent.floci.services.acm.CertificateGenerator - --initialize-at-run-time=io.github.hectorvent.floci.config.TlsConfigSource 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 7c6244d60c..bb00b84195 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 @@ -22,6 +22,8 @@ import java.security.KeyFactory; import java.security.MessageDigest; import java.security.PublicKey; import java.security.Signature; +import java.security.spec.MGF1ParameterSpec; +import java.security.spec.PSSParameterSpec; import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; import java.util.Base64; @@ -1258,6 +1260,53 @@ class KmsServiceTest { assertArrayEquals(rawSig, digestSig); } + @Test + void signWithDigestMessageTypePssVerifiesWithExternalVerifier() throws Exception { + KmsKey key = kmsService.createKey("rsa pss digest key", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION); + byte[] message = "floci kms pss round-trip".getBytes(StandardCharsets.UTF_8); + byte[] digest = MessageDigest.getInstance("SHA-256").digest(message); + + byte[] sig = kmsService.sign(key.getKeyId(), digest, + "RSASSA_PSS_SHA_256", KmsMessageType.DIGEST, REGION); + + // floci's own Verify round-trips, against the digest and against the raw message. + assertTrue(kmsService.verify(key.getKeyId(), digest, sig, + "RSASSA_PSS_SHA_256", KmsMessageType.DIGEST, REGION)); + assertTrue(kmsService.verify(key.getKeyId(), message, sig, + "RSASSA_PSS_SHA_256", KmsMessageType.RAW, REGION)); + + // External verifier with the PSS parameters AWS documents for RSASSA_PSS_SHA_256. + byte[] der = Base64.getDecoder().decode(kmsService.getPublicKey(key.getKeyId(), REGION).getPublicKeyEncoded()); + PublicKey pub = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(der)); + Signature verifier = Signature.getInstance("RSASSA-PSS"); + verifier.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1)); + verifier.initVerify(pub); + verifier.update(message); + assertTrue(verifier.verify(sig), "DIGEST PSS signature must verify as real RSASSA-PSS"); + } + + @Test + void signWithInvalidAlgorithmThrowsInvalidSigningAlgorithm() { + var key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION); + + var ex = assertThrows(AwsException.class, () -> + kmsService.sign(key.getKeyId(), "sign me".getBytes(StandardCharsets.UTF_8), "NOT_AN_ALGORITHM", REGION)); + + assertEquals("InvalidSigningAlgorithmException", ex.getErrorCode()); + } + + @Test + void verifyWithInvalidAlgorithmThrowsInvalidSigningAlgorithm() { + var key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION); + var message = "sign me".getBytes(StandardCharsets.UTF_8); + var sig = kmsService.sign(key.getKeyId(), message, "ECDSA_SHA_256", REGION); + + var ex = assertThrows(AwsException.class, () -> + kmsService.verify(key.getKeyId(), message, sig, "NOT_AN_ALGORITHM", REGION)); + + assertEquals("InvalidSigningAlgorithmException", ex.getErrorCode()); + } + @Test void verifyWithWrongSignatureReturnsFalse() { KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);