mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
refactor(acm): one issuer-signing primitive in CertificateGenerator (#3077)
* refactor(acm): one issuer-signing primitive in CertificateGenerator buildCertificate always signed with the subject's own key. signCertificate now takes the issuer DN and key explicitly; generateCaCertificate and generateIssuedCertificate sit on top of it, with serverAuth or clientAuth EKU on leaves. Existing public methods keep their signatures and output; metadata now follows ACM: colon-separated hex serial and the certificate's real signature algorithm in upper case. * refactor(cloudhsmv2): sign emulated hardware certificates through CertificateGenerator Deletes the private generateCert copy; the shared primitive also marks the two CA levels of the chain as CAs, which the old code did not. * refactor(acm): normalize imported certificate metadata and check issued key relationships ImportCertificate now stores the serial as colon-separated hex and the signature algorithm in upper case, the same shape generated certificates report. generateIssuedCertificate verifies the leaf against the issuer's certificate and refuses a supplied key pair whose halves do not match. * refactor(acm): refuse a supplied key pair that is not of the requested algorithm * refactor(acm): match a supplied EC key pair by named curve, not field size
This commit is contained in:
1 parent
0471d6f488
commit
4e05fdf582
5 files changed
+433
-110
No files matched your search
@@ -404,11 +404,11 @@ public class AcmService implements ResourceProvider {
|
||||
cert.setIssuedAt(now);
|
||||
cert.setNotBefore(x509Cert.getNotBefore().toInstant());
|
||||
cert.setNotAfter(x509Cert.getNotAfter().toInstant());
|
||||
cert.setSerial(x509Cert.getSerialNumber().toString());
|
||||
cert.setSerial(CertificateGenerator.colonHex(x509Cert.getSerialNumber()));
|
||||
cert.setSubject(x509Cert.getSubjectX500Principal().getName());
|
||||
cert.setIssuer(x509Cert.getIssuerX500Principal().getName());
|
||||
cert.setKeyAlgorithm(keyAlg);
|
||||
cert.setSignatureAlgorithm(x509Cert.getSigAlgName());
|
||||
cert.setSignatureAlgorithm(x509Cert.getSigAlgName().toUpperCase(Locale.ROOT));
|
||||
cert.setCertificateBody(certificatePem);
|
||||
cert.setPrivateKey(privateKeyPem);
|
||||
cert.setCertificateChain(chainPem);
|
||||
|
||||
@@ -7,10 +7,15 @@ 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.ExtendedKeyUsage;
|
||||
import org.bouncycastle.asn1.x509.Extension;
|
||||
import org.bouncycastle.asn1.x509.GeneralName;
|
||||
import org.bouncycastle.asn1.x509.GeneralNames;
|
||||
import org.bouncycastle.asn1.x509.KeyPurposeId;
|
||||
import org.bouncycastle.asn1.x509.KeyUsage;
|
||||
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
|
||||
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
|
||||
import org.bouncycastle.asn1.x9.X962Parameters;
|
||||
import org.bouncycastle.cert.X509CertificateHolder;
|
||||
import org.bouncycastle.cert.X509v3CertificateBuilder;
|
||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
|
||||
@@ -33,19 +38,23 @@ import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.math.BigInteger;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Security;
|
||||
import java.security.Signature;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.security.spec.ECGenParameterSpec;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -77,6 +86,16 @@ public class CertificateGenerator {
|
||||
String signatureAlgorithm
|
||||
) {}
|
||||
|
||||
/**
|
||||
* What an issued leaf is for. Decides the Extended Key Usage. A CA passes {@code null}.
|
||||
* {@code SERVER} carries both serverAuth and clientAuth, as ACM-issued certificates do (and as
|
||||
* {@code DescribeCertificate} already advertises); {@code CLIENT} is clientAuth only.
|
||||
*/
|
||||
public enum LeafUsage { SERVER, CLIENT }
|
||||
|
||||
/** A signer: the issuer's certificate (for its DN) and its private key. */
|
||||
public record Issuer(X509Certificate certificate, PrivateKey key) {}
|
||||
|
||||
/**
|
||||
* Generates a certificate for local emulation that mimics an ACM-issued certificate:
|
||||
* the subject is {@code CN=<domainName>} but the issuer is a cosmetic Amazon CA DN, matching
|
||||
@@ -115,88 +134,189 @@ public class CertificateGenerator {
|
||||
return buildCertificate(domainName, sans, keyAlgorithm, "CN=" + domainName, true, keyPair);
|
||||
}
|
||||
|
||||
/**
|
||||
* A root CA: self-signed, {@code cA=true}, {@code keyCertSign}, ten years. RSA 2048 because
|
||||
* every client in the emulator's reach accepts it and it keeps key generation under a second.
|
||||
*/
|
||||
public GeneratedCertificate generateCaCertificate(String commonName) {
|
||||
try {
|
||||
KeyPair keyPair = generateKeyPair(KeyAlgorithm.RSA_2048);
|
||||
X500Name dn = new X500Name("CN=" + commonName);
|
||||
X509Certificate cert = signCertificate(dn, keyPair.getPublic(), dn, keyPair.getPrivate(),
|
||||
List.of(), true, null, 3650);
|
||||
return toGenerated(cert, keyPair.getPrivate(), dn.toString(), dn.toString());
|
||||
} catch (Exception e) {
|
||||
LOG.error("Failed to generate CA certificate", e);
|
||||
throw new CertificateGenerationException("CA generation failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A leaf signed by {@code issuer}. {@code subjectKeyPair} may be {@code null} to mint a new
|
||||
* one of {@code keyAlgorithm}; pass the previous pair to reissue with an updated SAN list and
|
||||
* an unchanged public key, in which case it must be of {@code keyAlgorithm}. The result is
|
||||
* checked before it is returned: the leaf must verify against the issuer's certificate, and a
|
||||
* supplied key pair must be a pair of the requested algorithm, so a caller can never get back
|
||||
* a certificate its own issuer rejects, a private key that does not fit it, or a key type it
|
||||
* did not ask for.
|
||||
*/
|
||||
public GeneratedCertificate generateIssuedCertificate(String domainName, List<String> sans,
|
||||
KeyAlgorithm keyAlgorithm, KeyPair subjectKeyPair,
|
||||
Issuer issuer, LeafUsage usage) {
|
||||
try {
|
||||
if (subjectKeyPair != null && !isOfAlgorithm(subjectKeyPair.getPublic(), keyAlgorithm)) {
|
||||
throw new IllegalArgumentException("supplied key pair is not the requested " + keyAlgorithm);
|
||||
}
|
||||
if (subjectKeyPair != null && !isPair(subjectKeyPair.getPrivate(), subjectKeyPair.getPublic())) {
|
||||
throw new IllegalArgumentException("supplied private key does not match its public key");
|
||||
}
|
||||
KeyPair keyPair = subjectKeyPair != null ? subjectKeyPair : generateKeyPair(keyAlgorithm);
|
||||
X500Name subject = new X500Name("CN=" + domainName);
|
||||
X500Name issuerDn = X500Name.getInstance(issuer.certificate().getSubjectX500Principal().getEncoded());
|
||||
X509Certificate cert = signCertificate(subject, keyPair.getPublic(), issuerDn, issuer.key(),
|
||||
withDomainFirst(domainName, sans), false, usage, 365);
|
||||
cert.verify(issuer.certificate().getPublicKey());
|
||||
return toGenerated(cert, keyPair.getPrivate(), subject.toString(),
|
||||
issuer.certificate().getSubjectX500Principal().getName());
|
||||
} catch (Exception e) {
|
||||
LOG.error("Failed to generate issued certificate", e);
|
||||
throw new CertificateGenerationException("Certificate generation failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when {@code key} is exactly what {@code keyAlgorithm} names: the RSA size, or for EC the
|
||||
* named curve read from the key's encoding, so a curve that only shares a field size
|
||||
* (secp256k1 for {@code EC_prime256v1}) does not pass.
|
||||
*/
|
||||
boolean isOfAlgorithm(PublicKey key, KeyAlgorithm keyAlgorithm) {
|
||||
if ("EC".equals(keyAlgorithm.getAlgorithm())) {
|
||||
if (!"EC".equals(key.getAlgorithm())) {
|
||||
return false;
|
||||
}
|
||||
X962Parameters parameters = X962Parameters.getInstance(
|
||||
SubjectPublicKeyInfo.getInstance(key.getEncoded()).getAlgorithm().getParameters());
|
||||
return parameters.isNamedCurve()
|
||||
&& ECNamedCurveTable.getOID(keyAlgorithm.getCurveName()).equals(parameters.getParameters());
|
||||
}
|
||||
return "RSA".equals(key.getAlgorithm()) && detectKeyAlgorithm(key) == keyAlgorithm;
|
||||
}
|
||||
|
||||
/** True when {@code privateKey} signs what {@code publicKey} verifies. */
|
||||
public static boolean isPair(PrivateKey privateKey, PublicKey publicKey) throws Exception {
|
||||
String algorithm = "EC".equals(privateKey.getAlgorithm()) ? "SHA256withECDSA" : "SHA256withRSA";
|
||||
byte[] probe = "floci".getBytes(StandardCharsets.US_ASCII);
|
||||
Signature signer = Signature.getInstance(algorithm);
|
||||
signer.initSign(privateKey);
|
||||
signer.update(probe);
|
||||
byte[] signature = signer.sign();
|
||||
Signature verifier = Signature.getInstance(algorithm);
|
||||
verifier.initVerify(publicKey);
|
||||
verifier.update(probe);
|
||||
return verifier.verify(signature);
|
||||
}
|
||||
|
||||
private GeneratedCertificate buildCertificate(String domainName, List<String> sans, KeyAlgorithm keyAlgorithm,
|
||||
String issuerDn, boolean asCa, KeyPair suppliedKeyPair) {
|
||||
try {
|
||||
KeyPair keyPair = suppliedKeyPair != null ? suppliedKeyPair : generateKeyPair(keyAlgorithm);
|
||||
|
||||
Instant now = Instant.now();
|
||||
Instant notBefore = now;
|
||||
Instant notAfter = now.plus(365, ChronoUnit.DAYS);
|
||||
|
||||
BigInteger serial = new BigInteger(128, SECURE_RANDOM);
|
||||
String subjectDn = "CN=" + domainName;
|
||||
|
||||
X500Name issuer = new X500Name(issuerDn);
|
||||
X500Name subject = new X500Name(subjectDn);
|
||||
|
||||
String signatureAlgorithm = keyAlgorithm.getAlgorithm().equals("EC")
|
||||
? "SHA512withECDSA"
|
||||
: "SHA512WithRSA";
|
||||
|
||||
X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
|
||||
issuer,
|
||||
serial,
|
||||
Date.from(notBefore),
|
||||
Date.from(notAfter),
|
||||
subject,
|
||||
keyPair.getPublic()
|
||||
);
|
||||
|
||||
// Add Subject Alternative Names
|
||||
List<GeneralName> sanList = new ArrayList<>();
|
||||
sanList.add(toGeneralName(domainName));
|
||||
if (sans != null) {
|
||||
for (String san : sans) {
|
||||
if (!san.equals(domainName)) {
|
||||
sanList.add(toGeneralName(san));
|
||||
}
|
||||
}
|
||||
}
|
||||
GeneralNames generalNames = new GeneralNames(sanList.toArray(new GeneralName[0]));
|
||||
certBuilder.addExtension(Extension.subjectAlternativeName, false, generalNames);
|
||||
|
||||
// Add Key Usage — a trust-anchor self-signed cert also needs keyCertSign so it can
|
||||
// act as its own issuer; an ACM-style leaf only needs digitalSignature/keyEncipherment.
|
||||
int keyUsageBits = KeyUsage.digitalSignature | KeyUsage.keyEncipherment;
|
||||
if (asCa) {
|
||||
keyUsageBits |= KeyUsage.keyCertSign;
|
||||
}
|
||||
certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageBits));
|
||||
|
||||
// Add Basic Constraints — a trust anchor must be a CA so clients accept it as one.
|
||||
certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(asCa));
|
||||
|
||||
// Signed with the subject's own private key. For generateCertificate() the issuer DN is
|
||||
// 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)
|
||||
.build(keyPair.getPrivate());
|
||||
|
||||
X509CertificateHolder certHolder = certBuilder.build(signer);
|
||||
X509Certificate cert = new JcaX509CertificateConverter()
|
||||
.getCertificate(certHolder);
|
||||
|
||||
String certPem = toPem(cert);
|
||||
String keyPem = toPem(keyPair.getPrivate());
|
||||
|
||||
return new GeneratedCertificate(
|
||||
certPem,
|
||||
keyPem,
|
||||
serial.toString(),
|
||||
notBefore,
|
||||
notAfter,
|
||||
subjectDn,
|
||||
issuerDn,
|
||||
signatureAlgorithm
|
||||
);
|
||||
|
||||
// Signed with the subject's own key, as before: generateCertificate keeps its cosmetic
|
||||
// Amazon issuer DN, generateSelfSignedCertificate keeps issuer == subject.
|
||||
X509Certificate cert = signCertificate(new X500Name(subjectDn), keyPair.getPublic(),
|
||||
new X500Name(issuerDn), keyPair.getPrivate(), withDomainFirst(domainName, sans), asCa, null, 365);
|
||||
return toGenerated(cert, keyPair.getPrivate(), subjectDn, issuerDn);
|
||||
} catch (Exception e) {
|
||||
LOG.error("Failed to generate certificate", e);
|
||||
throw new CertificateGenerationException("Certificate generation failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The one place a certificate is signed. Everything else in this class, and
|
||||
* {@code CloudHsmV2Service}, goes through here.
|
||||
*
|
||||
* @param sans DNS names or IP addresses, written once each in order; empty for a CA
|
||||
* @param asCa sets {@code BasicConstraints(cA)}, {@code keyCertSign} and {@code cRLSign}
|
||||
* @param usage EKU for a leaf, {@code null} for a CA or a leaf without one
|
||||
*/
|
||||
public X509Certificate signCertificate(X500Name subject, PublicKey subjectKey, X500Name issuerDn,
|
||||
PrivateKey issuerKey, List<String> sans, boolean asCa,
|
||||
LeafUsage usage, int validityDays) throws Exception {
|
||||
Instant now = Instant.now();
|
||||
BigInteger serial = new BigInteger(128, SECURE_RANDOM);
|
||||
X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
|
||||
issuerDn, serial, Date.from(now), Date.from(now.plus(validityDays, ChronoUnit.DAYS)),
|
||||
subject, subjectKey);
|
||||
|
||||
if (sans != null && !sans.isEmpty()) {
|
||||
List<GeneralName> sanList = new ArrayList<>();
|
||||
for (String san : new LinkedHashSet<>(sans)) {
|
||||
sanList.add(toGeneralName(san));
|
||||
}
|
||||
certBuilder.addExtension(Extension.subjectAlternativeName, false,
|
||||
new GeneralNames(sanList.toArray(new GeneralName[0])));
|
||||
}
|
||||
|
||||
// keyEncipherment is an RSA key-transport bit; EC keys sign (and agree), they never encipher.
|
||||
int keyUsageBits = KeyUsage.digitalSignature;
|
||||
if ("RSA".equals(subjectKey.getAlgorithm())) {
|
||||
keyUsageBits |= KeyUsage.keyEncipherment;
|
||||
}
|
||||
if (asCa) {
|
||||
keyUsageBits |= KeyUsage.keyCertSign | KeyUsage.cRLSign;
|
||||
}
|
||||
certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageBits));
|
||||
certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(asCa));
|
||||
if (usage == LeafUsage.SERVER) {
|
||||
certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(
|
||||
new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth}));
|
||||
} else if (usage == LeafUsage.CLIENT) {
|
||||
certBuilder.addExtension(Extension.extendedKeyUsage, false,
|
||||
new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
|
||||
}
|
||||
|
||||
String signatureAlgorithm = "EC".equals(issuerKey.getAlgorithm()) ? "SHA512withECDSA" : "SHA512WithRSA";
|
||||
ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(issuerKey);
|
||||
X509CertificateHolder holder = certBuilder.build(signer);
|
||||
return new JcaX509CertificateConverter().getCertificate(holder);
|
||||
}
|
||||
|
||||
private static List<String> withDomainFirst(String domainName, List<String> sans) {
|
||||
List<String> allSans = new ArrayList<>();
|
||||
allSans.add(domainName);
|
||||
if (sans != null) {
|
||||
allSans.addAll(sans);
|
||||
}
|
||||
return allSans;
|
||||
}
|
||||
|
||||
/**
|
||||
* Metadata comes from the certificate, not from the arguments: the signature algorithm is the
|
||||
* issuer's (an RSA CA signing an EC leaf yields SHA512WITHRSA, spelled in upper case as ACM
|
||||
* does), and ACM shows the serial as colon-separated hex ({@code 07:71:71:f4:...}).
|
||||
*/
|
||||
private GeneratedCertificate toGenerated(X509Certificate cert, PrivateKey key, String subjectDn,
|
||||
String issuerDn) throws Exception {
|
||||
return new GeneratedCertificate(
|
||||
toPem(cert),
|
||||
toPem(key),
|
||||
colonHex(cert.getSerialNumber()),
|
||||
cert.getNotBefore().toInstant(),
|
||||
cert.getNotAfter().toInstant(),
|
||||
subjectDn,
|
||||
issuerDn,
|
||||
cert.getSigAlgName().toUpperCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
static String colonHex(BigInteger serial) {
|
||||
String hex = serial.toString(16);
|
||||
if (hex.length() % 2 == 1) {
|
||||
hex = "0" + hex;
|
||||
}
|
||||
return String.join(":", hex.split("(?<=\\G..)"));
|
||||
}
|
||||
|
||||
private KeyPair generateKeyPair(KeyAlgorithm keyAlgorithm) throws Exception {
|
||||
KeyPairGenerator keyGen;
|
||||
if ("EC".equals(keyAlgorithm.getAlgorithm())) {
|
||||
@@ -244,7 +364,7 @@ public class CertificateGenerator {
|
||||
return IP_ADDRESS_PATTERN.matcher(value).matches();
|
||||
}
|
||||
|
||||
private String toPem(Object obj) throws Exception {
|
||||
public String toPem(Object obj) throws Exception {
|
||||
StringWriter sw = new StringWriter();
|
||||
try (JcaPEMWriter pemWriter = new JcaPEMWriter(sw)) {
|
||||
pemWriter.writeObject(obj);
|
||||
|
||||
+18
-35
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.cloudhsmv2.model.Certificates;
|
||||
import io.github.hectorvent.floci.services.cloudhsmv2.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.cloudhsmv2.model.ClusterState;
|
||||
@@ -11,9 +12,7 @@ import io.github.hectorvent.floci.services.cloudhsmv2.model.Hsm;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.bouncycastle.asn1.x500.X500Name;
|
||||
import org.bouncycastle.cert.X509v3CertificateBuilder;
|
||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
|
||||
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
|
||||
|
||||
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
|
||||
import org.bouncycastle.operator.ContentSigner;
|
||||
@@ -27,15 +26,11 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.math.BigInteger;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.cert.X509Certificate;
|
||||
import io.github.hectorvent.floci.services.cloudhsmv2.model.Backup;
|
||||
import io.github.hectorvent.floci.services.cloudhsmv2.model.BackupRetentionPolicy;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.time.Instant;
|
||||
@@ -64,20 +59,24 @@ public class CloudHsmV2Service {
|
||||
private final StorageBackend<String, Cluster> clusters;
|
||||
private final StorageBackend<String, Backup> backups;
|
||||
private final Ec2Service ec2Service;
|
||||
private final CertificateGenerator certificateGenerator;
|
||||
|
||||
@Inject
|
||||
public CloudHsmV2Service(StorageFactory storageFactory, Ec2Service ec2Service) {
|
||||
this.clusters = storageFactory.create("cloudhsmv2", "cloudhsmv2-clusters.json",
|
||||
new TypeReference<Map<String, Cluster>>() {});
|
||||
this.backups = storageFactory.create("cloudhsmv2", "cloudhsmv2-backups.json",
|
||||
new TypeReference<Map<String, Backup>>() {});
|
||||
this.ec2Service = ec2Service;
|
||||
public CloudHsmV2Service(StorageFactory storageFactory, Ec2Service ec2Service,
|
||||
CertificateGenerator certificateGenerator) {
|
||||
this(storageFactory.create("cloudhsmv2", "cloudhsmv2-clusters.json",
|
||||
new TypeReference<Map<String, Cluster>>() {}),
|
||||
storageFactory.create("cloudhsmv2", "cloudhsmv2-backups.json",
|
||||
new TypeReference<Map<String, Backup>>() {}),
|
||||
ec2Service, certificateGenerator);
|
||||
}
|
||||
|
||||
CloudHsmV2Service(StorageBackend<String, Cluster> clusters, StorageBackend<String, Backup> backups, Ec2Service ec2Service) {
|
||||
CloudHsmV2Service(StorageBackend<String, Cluster> clusters, StorageBackend<String, Backup> backups,
|
||||
Ec2Service ec2Service, CertificateGenerator certificateGenerator) {
|
||||
this.clusters = clusters;
|
||||
this.backups = backups;
|
||||
this.ec2Service = ec2Service;
|
||||
this.certificateGenerator = certificateGenerator;
|
||||
}
|
||||
|
||||
// ──────────────────────────── CreateCluster ────────────────────────────
|
||||
@@ -173,15 +172,18 @@ public class CloudHsmV2Service {
|
||||
try {
|
||||
KeyPair mfrKeyPair = generateKeyPair();
|
||||
X500Name mfrName = new X500Name("CN=HSM Manufacturer CA,O=AWS,C=US");
|
||||
certs.setManufacturerHardwareCertificate(generateCert(mfrName, mfrName, mfrKeyPair.getPublic(), mfrKeyPair.getPrivate()));
|
||||
certs.setManufacturerHardwareCertificate(certificateGenerator.toPem(certificateGenerator.signCertificate(
|
||||
mfrName, mfrKeyPair.getPublic(), mfrName, mfrKeyPair.getPrivate(), List.of(), true, null, 365)));
|
||||
|
||||
KeyPair awsKeyPair = generateKeyPair();
|
||||
X500Name awsName = new X500Name("CN=AWS CloudHSM Hardware CA,O=AWS,C=US");
|
||||
certs.setAwsHardwareCertificate(generateCert(awsName, mfrName, awsKeyPair.getPublic(), mfrKeyPair.getPrivate()));
|
||||
certs.setAwsHardwareCertificate(certificateGenerator.toPem(certificateGenerator.signCertificate(
|
||||
awsName, awsKeyPair.getPublic(), mfrName, mfrKeyPair.getPrivate(), List.of(), true, null, 365)));
|
||||
|
||||
KeyPair hsmKeyPair = generateKeyPair();
|
||||
X500Name hsmName = new X500Name("CN=HSM Instance " + clusterId + ",O=AWS,C=US");
|
||||
certs.setHsmCertificate(generateCert(hsmName, awsName, hsmKeyPair.getPublic(), awsKeyPair.getPrivate()));
|
||||
certs.setHsmCertificate(certificateGenerator.toPem(certificateGenerator.signCertificate(
|
||||
hsmName, hsmKeyPair.getPublic(), awsName, awsKeyPair.getPrivate(), List.of(), false, null, 365)));
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to generate emulated hardware certs: {0}", e.getMessage());
|
||||
}
|
||||
@@ -534,25 +536,6 @@ public class CloudHsmV2Service {
|
||||
return keyGen.generateKeyPair();
|
||||
}
|
||||
|
||||
private String generateCert(X500Name subject, X500Name issuer, PublicKey pubKey, PrivateKey signerKey) throws Exception {
|
||||
BigInteger serial = new BigInteger(128, SECURE_RANDOM);
|
||||
Instant now = Instant.now();
|
||||
X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
|
||||
issuer, serial, Date.from(now), Date.from(now.plusSeconds(365L * 24 * 3600)), subject, pubKey);
|
||||
|
||||
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA")
|
||||
.build(signerKey);
|
||||
X509CertificateHolder holder = certBuilder.build(signer);
|
||||
X509Certificate cert = new JcaX509CertificateConverter()
|
||||
.getCertificate(holder);
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
try (JcaPEMWriter pemWriter = new JcaPEMWriter(sw)) {
|
||||
pemWriter.writeObject(cert);
|
||||
}
|
||||
return sw.toString();
|
||||
}
|
||||
|
||||
private void validatePemCertificate(String pem, String fieldName) {
|
||||
if (pem == null || pem.isBlank()) {
|
||||
throw new AwsException("CloudHsmInvalidRequestException",
|
||||
|
||||
Reference in new issue
Block a user