mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(iot): real device certificates issued by the local CA (#3079)
* feat(iot): CreateKeysAndCertificate issues a real client certificate from the local CA certificateId is sha256(DER) in lowercase hex as on AWS; the returned RSA 2048 key pair matches the certificate. CreateCertificateFromCsr parses the PKCS#10, checks its self-signature and key strength (RSA 2048 or more, EC P-256/384/521), signs the CSR's key with the same CA and returns no private key, as on AWS. * docs(iot): describe the CA-issued device certificates * fix(iot): accept only the NIST curves AWS IoT names and never store a device private key The CSR key check reads the named-curve identifier instead of the field size, so secp256k1 and explicit curve parameters are refused as on AWS. The stored certificate record no longer carries the private key; it is returned once. * feat(iot): device certificates expire at the end of 2049 and DescribeCertificate reports validity AWS IoT-issued client certificates all carry notAfter 2049-12-31T23:59:59Z. CertificateGenerator gains an overload with an explicit validity window; DescribeCertificate adds validity.notBefore, validity.notAfter and certificateMode DEFAULT. The Java SDK compatibility test asserts the shape. * fix(iot): a device certificate never outlives its issuing CA A new local CA is valid until the end of 2050, past AWS's fixed 2049 device expiry; a CA created earlier (ten years) caps the device certificates it signs at its own expiry, so a chain never expires before its leaf. * fix(iot): derive CA and device expiry from creation time, never mint an expired certificate A CA created after 2050 lives ten years from creation instead of ending on the fixed date; after 2049 a device certificate lives a year, still capped at its CA. The Python compatibility suite now sends a real PKCS#10 request, since the placeholder it used is refused as on AWS. * docs(tls): the local CA now signs IoT device certificates * test(iot): pass the certificate authority to IotServiceTest's constructor
This commit is contained in:
1 parent
bf517ac952
commit
c67e598594
13 files changed
+711
-35
No files matched your search
@@ -2,9 +2,22 @@ package io.github.hectorvent.floci.config;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
|
||||
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
|
||||
import org.bouncycastle.asn1.pkcs.RSAPublicKey;
|
||||
import org.bouncycastle.asn1.sec.SECObjectIdentifiers;
|
||||
import org.bouncycastle.asn1.x500.X500Name;
|
||||
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
|
||||
import org.bouncycastle.asn1.x9.X962Parameters;
|
||||
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
|
||||
import org.bouncycastle.openssl.PEMParser;
|
||||
import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder;
|
||||
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
|
||||
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFileAttributeView;
|
||||
@@ -14,8 +27,10 @@ import java.security.PrivateKey;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.PublicKey;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Floci's one local root CA. Every certificate the emulator hands out that a client is expected
|
||||
@@ -33,6 +48,12 @@ public final class FlociCertificateAuthority {
|
||||
public static final String CA_CERT_NAME = "floci-root-ca.crt";
|
||||
public static final String CA_KEY_NAME = "floci-root-ca.key";
|
||||
static final String COMMON_NAME = "Floci Local CA";
|
||||
/** AWS IoT-issued client certificates all expire at this instant, whenever they were created. */
|
||||
public static final Instant DEVICE_CERTIFICATE_NOT_AFTER = Instant.parse("2049-12-31T23:59:59Z");
|
||||
/** A new CA outlives every device certificate it will sign, so a chain never expires before its leaf. */
|
||||
static final Instant CA_NOT_AFTER = Instant.parse("2050-12-31T23:59:59Z");
|
||||
private static final long TEN_YEARS_IN_DAYS = 3650;
|
||||
private static final long ONE_YEAR_IN_DAYS = 365;
|
||||
|
||||
private final Path certificatePath;
|
||||
private final X509Certificate certificate;
|
||||
@@ -85,7 +106,7 @@ public final class FlociCertificateAuthority {
|
||||
}
|
||||
Files.createDirectories(tlsDir);
|
||||
restrictToOwnerOnly(tlsDir, "rwx------");
|
||||
CertificateGenerator.GeneratedCertificate generated = generator.generateCaCertificate(COMMON_NAME);
|
||||
CertificateGenerator.GeneratedCertificate generated = generator.generateCaCertificate(COMMON_NAME, caNotAfter(Instant.now()));
|
||||
Files.writeString(certFile, generated.certificatePem());
|
||||
writePrivateKey(keyFile, generated.privateKeyPem());
|
||||
FlociCertificateAuthority ca = new FlociCertificateAuthority(certFile,
|
||||
@@ -145,10 +166,62 @@ public final class FlociCertificateAuthority {
|
||||
CertificateGenerator.LeafUsage.SERVER);
|
||||
}
|
||||
|
||||
/** A {@code clientAuth} leaf, for IoT device certificates. Always a fresh RSA 2048 key pair. */
|
||||
/**
|
||||
* A {@code clientAuth} leaf for an IoT device: a fresh RSA 2048 key pair and, as on AWS, validity
|
||||
* until the end of 2049, never past the CA's own expiry.
|
||||
*/
|
||||
public CertificateGenerator.GeneratedCertificate issueClientCertificate(String commonName) {
|
||||
return generator.generateIssuedCertificate(commonName, List.of(), KeyAlgorithm.RSA_2048, null, issuer(),
|
||||
CertificateGenerator.LeafUsage.CLIENT);
|
||||
CertificateGenerator.LeafUsage.CLIENT, deviceCertificateNotAfter());
|
||||
}
|
||||
|
||||
/**
|
||||
* The end of validity for a device certificate: AWS's fixed 2049 date, capped at the CA's own
|
||||
* expiry so a CA created before that date was adopted (ten years) never signs a leaf that
|
||||
* outlives it. Once 2049 has passed, one year from now, the same cap applied.
|
||||
*/
|
||||
public Instant deviceCertificateNotAfter() {
|
||||
return deviceCertificateNotAfter(Instant.now());
|
||||
}
|
||||
|
||||
Instant deviceCertificateNotAfter(Instant now) {
|
||||
Instant caNotAfter = certificate.getNotAfter().toInstant();
|
||||
Instant wanted = DEVICE_CERTIFICATE_NOT_AFTER.isAfter(now)
|
||||
? DEVICE_CERTIFICATE_NOT_AFTER
|
||||
: now.plus(ONE_YEAR_IN_DAYS, java.time.temporal.ChronoUnit.DAYS);
|
||||
return caNotAfter.isBefore(wanted) ? caNotAfter : wanted;
|
||||
}
|
||||
|
||||
/** A new CA ends in 2050, or ten years from now when that is later, so it is never born expired. */
|
||||
static Instant caNotAfter(Instant now) {
|
||||
Instant tenYears = now.plus(TEN_YEARS_IN_DAYS, java.time.temporal.ChronoUnit.DAYS);
|
||||
return tenYears.isAfter(CA_NOT_AFTER) ? tenYears : CA_NOT_AFTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs an external PKCS#10 request as a {@code clientAuth} leaf. The subject DN comes from
|
||||
* the CSR; requested extensions are ignored (AWS IoT ignores them too). Throws
|
||||
* {@link IllegalArgumentException} when the PEM is not a CSR or its self-signature fails.
|
||||
*/
|
||||
public X509Certificate signClientCsr(String csrPem) {
|
||||
try (PEMParser parser = new PEMParser(new StringReader(csrPem))) {
|
||||
Object parsed = parser.readObject();
|
||||
if (!(parsed instanceof PKCS10CertificationRequest csr)) {
|
||||
throw new IllegalArgumentException("certificateSigningRequest is not a PEM CERTIFICATE REQUEST");
|
||||
}
|
||||
requireAcceptedKey(csr.getSubjectPublicKeyInfo());
|
||||
PublicKey subjectKey = new JcaPKCS10CertificationRequest(csr).getPublicKey();
|
||||
if (!csr.isSignatureValid(new JcaContentVerifierProviderBuilder().build(subjectKey))) {
|
||||
throw new IllegalArgumentException("certificateSigningRequest signature does not verify");
|
||||
}
|
||||
X500Name issuerDn = X500Name.getInstance(certificate.getSubjectX500Principal().getEncoded());
|
||||
return generator.signCertificate(csr.getSubject(), subjectKey, issuerDn, key, List.of(), false,
|
||||
CertificateGenerator.LeafUsage.CLIENT, Instant.now(), deviceCertificateNotAfter());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException("certificateSigningRequest could not be parsed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/** True when {@code cert} names this CA as issuer and its signature checks against our key. */
|
||||
@@ -165,6 +238,30 @@ public final class FlociCertificateAuthority {
|
||||
}
|
||||
}
|
||||
|
||||
private static final Set<ASN1ObjectIdentifier> ACCEPTED_CURVES = Set.of(
|
||||
SECObjectIdentifiers.secp256r1, SECObjectIdentifiers.secp384r1, SECObjectIdentifiers.secp521r1);
|
||||
|
||||
/**
|
||||
* AWS IoT accepts an RSA key of at least 2048 bits or an EC key on NIST P-256, P-384 or P-521.
|
||||
* The curve is read from the request's named-curve identifier, so a curve that merely shares a
|
||||
* field size (secp256k1) or explicit curve parameters are refused as well.
|
||||
*/
|
||||
private static void requireAcceptedKey(SubjectPublicKeyInfo key) throws Exception {
|
||||
ASN1ObjectIdentifier algorithm = key.getAlgorithm().getAlgorithm();
|
||||
if (PKCSObjectIdentifiers.rsaEncryption.equals(algorithm)
|
||||
&& RSAPublicKey.getInstance(key.parsePublicKey()).getModulus().bitLength() >= 2048) {
|
||||
return;
|
||||
}
|
||||
if (X9ObjectIdentifiers.id_ecPublicKey.equals(algorithm)) {
|
||||
X962Parameters parameters = X962Parameters.getInstance(key.getAlgorithm().getParameters());
|
||||
if (parameters.isNamedCurve() && ACCEPTED_CURVES.contains((ASN1ObjectIdentifier) parameters.getParameters())) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("certificateSigningRequest key must be RSA of at least 2048 bits "
|
||||
+ "or EC on NIST P-256, P-384 or P-521");
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a private key so that, where the file system has POSIX permissions, no other user can
|
||||
* read it at any point: the file is created owner-only before the first byte is written. A
|
||||
|
||||
@@ -125,11 +125,16 @@ public class CertificateGenerator {
|
||||
* every client in the emulator's reach accepts it and it keeps key generation under a second.
|
||||
*/
|
||||
public GeneratedCertificate generateCaCertificate(String commonName) {
|
||||
return generateCaCertificate(commonName, Instant.now().plus(3650, ChronoUnit.DAYS));
|
||||
}
|
||||
|
||||
/** Same as {@link #generateCaCertificate(String)} with an explicit end of validity. */
|
||||
public GeneratedCertificate generateCaCertificate(String commonName, Instant notAfter) {
|
||||
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);
|
||||
List.of(), true, null, Instant.now(), notAfter);
|
||||
return toGenerated(cert, keyPair.getPrivate(), dn.toString(), dn.toString());
|
||||
} catch (Exception e) {
|
||||
LOG.error("Failed to generate CA certificate", e);
|
||||
@@ -149,6 +154,14 @@ public class CertificateGenerator {
|
||||
public GeneratedCertificate generateIssuedCertificate(String domainName, List<String> sans,
|
||||
KeyAlgorithm keyAlgorithm, KeyPair subjectKeyPair,
|
||||
Issuer issuer, LeafUsage usage) {
|
||||
return generateIssuedCertificate(domainName, sans, keyAlgorithm, subjectKeyPair, issuer, usage,
|
||||
Instant.now().plus(365, ChronoUnit.DAYS));
|
||||
}
|
||||
|
||||
/** Same as {@link #generateIssuedCertificate(String, List, KeyAlgorithm, KeyPair, Issuer, LeafUsage)} with an explicit end of validity. */
|
||||
public GeneratedCertificate generateIssuedCertificate(String domainName, List<String> sans,
|
||||
KeyAlgorithm keyAlgorithm, KeyPair subjectKeyPair,
|
||||
Issuer issuer, LeafUsage usage, Instant notAfter) {
|
||||
try {
|
||||
if (subjectKeyPair != null && !isOfAlgorithm(subjectKeyPair.getPublic(), keyAlgorithm)) {
|
||||
throw new IllegalArgumentException("supplied key pair is not the requested " + keyAlgorithm);
|
||||
@@ -160,7 +173,7 @@ public class CertificateGenerator {
|
||||
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);
|
||||
withDomainFirst(domainName, sans), false, usage, Instant.now(), notAfter);
|
||||
cert.verify(issuer.certificate().getPublicKey());
|
||||
return toGenerated(cert, keyPair.getPrivate(), subject.toString(),
|
||||
issuer.certificate().getSubjectX500Principal().getName());
|
||||
@@ -229,10 +242,17 @@ public class CertificateGenerator {
|
||||
PrivateKey issuerKey, List<String> sans, boolean asCa,
|
||||
LeafUsage usage, int validityDays) throws Exception {
|
||||
Instant now = Instant.now();
|
||||
return signCertificate(subject, subjectKey, issuerDn, issuerKey, sans, asCa, usage, now,
|
||||
now.plus(validityDays, ChronoUnit.DAYS));
|
||||
}
|
||||
|
||||
/** Same as {@link #signCertificate(X500Name, PublicKey, X500Name, PrivateKey, List, boolean, LeafUsage, int)} with an explicit validity window. */
|
||||
public X509Certificate signCertificate(X500Name subject, PublicKey subjectKey, X500Name issuerDn,
|
||||
PrivateKey issuerKey, List<String> sans, boolean asCa,
|
||||
LeafUsage usage, Instant notBefore, Instant notAfter) throws Exception {
|
||||
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);
|
||||
issuerDn, serial, Date.from(notBefore), Date.from(notAfter), subject, subjectKey);
|
||||
|
||||
if (sans != null && !sans.isEmpty()) {
|
||||
List<GeneralName> sanList = new ArrayList<>();
|
||||
|
||||
@@ -945,7 +945,13 @@ public class IotController {
|
||||
description.put("certificateId", certificate.getCertificateId());
|
||||
description.put("certificatePem", certificate.getCertificatePem());
|
||||
description.put("status", certificate.getStatus());
|
||||
description.put("certificateMode", "DEFAULT");
|
||||
putEpoch(description, "creationDate", certificate.getCreationDate());
|
||||
if (certificate.getNotBefore() != null && certificate.getNotAfter() != null) {
|
||||
ObjectNode validity = description.putObject("validity");
|
||||
putEpoch(validity, "notBefore", certificate.getNotBefore());
|
||||
putEpoch(validity, "notAfter", certificate.getNotAfter());
|
||||
}
|
||||
return description;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -22,6 +23,7 @@ import io.github.hectorvent.floci.services.iot.model.IotShadow;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotThingGroup;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotThingType;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotTopicRule;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.iot.model.Thing;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
|
||||
import io.github.hectorvent.floci.services.firehose.FirehoseService;
|
||||
@@ -39,12 +41,15 @@ import org.jboss.logging.Logger;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -92,6 +97,7 @@ public class IotService {
|
||||
private final LambdaService lambdaService;
|
||||
private final FirehoseService firehoseService;
|
||||
private final CloudWatchLogsService cloudWatchLogsService;
|
||||
private final FlociCertificateAuthority certificateAuthority;
|
||||
|
||||
@Inject
|
||||
public IotService(StorageFactory storageFactory,
|
||||
@@ -107,7 +113,8 @@ public class IotService {
|
||||
DynamoDbService dynamoDbService,
|
||||
LambdaService lambdaService,
|
||||
FirehoseService firehoseService,
|
||||
CloudWatchLogsService cloudWatchLogsService) {
|
||||
CloudWatchLogsService cloudWatchLogsService,
|
||||
FlociCertificateAuthority certificateAuthority) {
|
||||
this(storageFactory.create("iot", "iot-things.json", new TypeReference<Map<String, Thing>>() {}),
|
||||
storageFactory.create("iot", "iot-certificates.json", new TypeReference<Map<String, IotCertificate>>() {}),
|
||||
storageFactory.create("iot", "iot-policies.json", new TypeReference<Map<String, IotPolicy>>() {}),
|
||||
@@ -122,7 +129,7 @@ public class IotService {
|
||||
storageFactory.create("iot", "iot-thing-groups.json", new TypeReference<Map<String, IotThingGroup>>() {}),
|
||||
storageFactory.create("iot", "iot-thing-group-memberships.json", new TypeReference<Map<String, Set<String>>>() {}),
|
||||
config, regionResolver, objectMapper, publishEventRecorder, mqttBrokerService, sqsService, snsService,
|
||||
s3Service, kinesisService, dynamoDbService, lambdaService, firehoseService, cloudWatchLogsService);
|
||||
s3Service, kinesisService, dynamoDbService, lambdaService, firehoseService, cloudWatchLogsService, certificateAuthority);
|
||||
}
|
||||
|
||||
IotService(StorageBackend<String, Thing> thingStore,
|
||||
@@ -150,7 +157,8 @@ public class IotService {
|
||||
DynamoDbService dynamoDbService,
|
||||
LambdaService lambdaService,
|
||||
FirehoseService firehoseService,
|
||||
CloudWatchLogsService cloudWatchLogsService) {
|
||||
CloudWatchLogsService cloudWatchLogsService,
|
||||
FlociCertificateAuthority certificateAuthority) {
|
||||
this.thingStore = thingStore;
|
||||
this.certificateStore = certificateStore;
|
||||
this.policyStore = policyStore;
|
||||
@@ -177,6 +185,7 @@ public class IotService {
|
||||
this.lambdaService = lambdaService;
|
||||
this.firehoseService = firehoseService;
|
||||
this.cloudWatchLogsService = cloudWatchLogsService;
|
||||
this.certificateAuthority = certificateAuthority;
|
||||
}
|
||||
|
||||
public String describeEndpoint(String endpointType) {
|
||||
@@ -297,19 +306,70 @@ public class IotService {
|
||||
|
||||
private IotCertificate createCertificate(boolean setAsActive, String certificateSigningRequest, String region) {
|
||||
startMqttIfEnabled();
|
||||
String id = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
|
||||
IotCertificate certificate = new IotCertificate();
|
||||
certificate.setCertificateId(id);
|
||||
certificate.setCertificateArn(regionResolver.buildArn("iot", region, "cert/" + id));
|
||||
certificate.setCertificatePem("-----BEGIN CERTIFICATE-----\n" + id + "\n-----END CERTIFICATE-----");
|
||||
certificate.setPublicKey("-----BEGIN PUBLIC KEY-----\n" + (certificateSigningRequest == null ? id : certificateSigningRequest.hashCode()) + "\n-----END PUBLIC KEY-----");
|
||||
certificate.setPrivateKey("-----BEGIN PRIVATE KEY-----\n" + id + "\n-----END PRIVATE KEY-----");
|
||||
if (certificateSigningRequest == null) {
|
||||
issueFromLocalCa(certificate);
|
||||
} else {
|
||||
issueFromCsr(certificate, certificateSigningRequest);
|
||||
}
|
||||
certificate.setCertificateArn(regionResolver.buildArn("iot", region, "cert/" + certificate.getCertificateId()));
|
||||
certificate.setStatus(setAsActive ? "ACTIVE" : "INACTIVE");
|
||||
certificate.setCreationDate(Instant.now());
|
||||
certificateStore.put(certificateKey(region, id), certificate);
|
||||
certificateStore.put(certificateKey(region, certificate.getCertificateId()), withoutPrivateKey(certificate));
|
||||
return certificate;
|
||||
}
|
||||
|
||||
/** As on AWS, the private key is returned once and never kept: the stored record has none. */
|
||||
private static IotCertificate withoutPrivateKey(IotCertificate certificate) {
|
||||
IotCertificate stored = new IotCertificate();
|
||||
stored.setCertificateId(certificate.getCertificateId());
|
||||
stored.setCertificateArn(certificate.getCertificateArn());
|
||||
stored.setCertificatePem(certificate.getCertificatePem());
|
||||
stored.setPublicKey(certificate.getPublicKey());
|
||||
stored.setStatus(certificate.getStatus());
|
||||
stored.setCreationDate(certificate.getCreationDate());
|
||||
stored.setNotBefore(certificate.getNotBefore());
|
||||
stored.setNotAfter(certificate.getNotAfter());
|
||||
stored.setTags(certificate.getTags());
|
||||
return stored;
|
||||
}
|
||||
|
||||
/** As on AWS: a fresh RSA 2048 pair, the subject {@code AWS IoT Certificate}, and the private key returned once. */
|
||||
private void issueFromLocalCa(IotCertificate certificate) {
|
||||
CertificateGenerator.GeneratedCertificate issued = certificateAuthority.issueClientCertificate("AWS IoT Certificate");
|
||||
try {
|
||||
fill(certificate, new CertificateGenerator().parseCertificate(issued.certificatePem()));
|
||||
certificate.setPrivateKey(issued.privateKeyPem());
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InternalFailureException", "Could not issue device certificate: " + e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
/** The device keeps its key: only the certificate and its public key are stored. */
|
||||
private void issueFromCsr(IotCertificate certificate, String csrPem) {
|
||||
X509Certificate x509;
|
||||
try {
|
||||
x509 = certificateAuthority.signClientCsr(csrPem);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidRequestException", e.getMessage(), 400);
|
||||
}
|
||||
try {
|
||||
fill(certificate, x509);
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InternalFailureException", "Could not encode device certificate: " + e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
/** AWS IoT's certificateId is the lowercase hex SHA-256 of the certificate's DER encoding. */
|
||||
private static void fill(IotCertificate certificate, X509Certificate x509) throws Exception {
|
||||
CertificateGenerator pem = new CertificateGenerator();
|
||||
certificate.setCertificateId(HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(x509.getEncoded())));
|
||||
certificate.setCertificatePem(pem.toPem(x509));
|
||||
certificate.setPublicKey(pem.toPem(x509.getPublicKey()));
|
||||
certificate.setNotBefore(x509.getNotBefore().toInstant());
|
||||
certificate.setNotAfter(x509.getNotAfter().toInstant());
|
||||
}
|
||||
|
||||
public IotCertificate describeCertificate(String certificateId, String region) {
|
||||
return certificateStore.get(certificateKey(region, certificateId))
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Certificate not found: " + certificateId, 404));
|
||||
|
||||
@@ -15,6 +15,8 @@ public class IotCertificate {
|
||||
private String privateKey;
|
||||
private String status;
|
||||
private Instant creationDate;
|
||||
private Instant notBefore;
|
||||
private Instant notAfter;
|
||||
private Map<String, String> tags = new TreeMap<>();
|
||||
|
||||
public String getCertificateId() { return certificateId; }
|
||||
@@ -31,6 +33,10 @@ public class IotCertificate {
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public Instant getCreationDate() { return creationDate; }
|
||||
public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; }
|
||||
public Instant getNotBefore() { return notBefore; }
|
||||
public void setNotBefore(Instant notBefore) { this.notBefore = notBefore; }
|
||||
public Instant getNotAfter() { return notAfter; }
|
||||
public void setNotAfter(Instant notAfter) { this.notAfter = notAfter; }
|
||||
public Map<String, String> getTags() { return tags == null ? Map.of() : tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags == null ? new TreeMap<>() : new TreeMap<>(tags); }
|
||||
}
|
||||
Reference in new issue
Block a user