use of org.openecard.bouncycastle.asn1.x509.Certificate in project curiostack by curioswitch.
the class RequestNamespaceCertTask method exec.
@TaskAction
public void exec() {
ImmutableClusterExtension cluster = getProject().getExtensions().getByType(ClusterExtension.class);
final KeyPairGenerator keygen;
try {
keygen = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
throw new IllegalStateException("Could not find RSA, can't happen.", e);
}
keygen.initialize(256, new SecureRandom());
KeyPair keyPair = keygen.generateKeyPair();
PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Principal("CN=" + cluster.namespace() + ".ns.cluster.stellarstation.com"), keyPair.getPublic());
Stream<GeneralName> generalNames = Streams.concat(Stream.of(new GeneralName(GeneralName.dNSName, "*." + cluster.namespace()), new GeneralName(GeneralName.dNSName, "*." + cluster.namespace() + ".svc"), new GeneralName(GeneralName.dNSName, "*." + cluster.namespace() + ".svc.cluster.local")), cluster.extraNamespaceTlsHosts().stream().map(name -> new GeneralName(GeneralName.dNSName, name)));
GeneralNames subjectAltNames = new GeneralNames(generalNames.toArray(GeneralName[]::new));
ExtensionsGenerator extensions = new ExtensionsGenerator();
try {
extensions.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
p10Builder.setAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions.generate());
} catch (IOException e) {
throw new IllegalStateException("Could not encode cert name, can't happen.", e);
}
final ContentSigner signer;
try {
signer = new JcaContentSignerBuilder("SHA256withECDSA").build(keyPair.getPrivate());
} catch (OperatorCreationException e) {
throw new IllegalStateException("Could not find signer, can't happen.", e);
}
PKCS10CertificationRequest csr = p10Builder.build(signer);
StringWriter csrWriter = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(csrWriter)) {
pemWriter.writeObject(csr);
} catch (IOException e) {
throw new IllegalStateException("Could not encode csr, can't happen.", e);
}
String encodedCsr = Base64.getEncoder().encodeToString(csrWriter.toString().getBytes(StandardCharsets.UTF_8));
Map<Object, Object> csrApiRequest = ImmutableMap.of("apiVersion", "certificates.k8s.io/v1beta1", "kind", "CertificateSigningRequest", "metadata", ImmutableMap.of("name", cluster.namespace() + ".server.crt"), "spec", ImmutableMap.of("request", encodedCsr, "usages", ImmutableList.of("digital signature", "key encipherment", "server auth", "client auth")));
final byte[] encodedApiRequest;
try {
encodedApiRequest = OBJECT_MAPPER.writeValueAsBytes(csrApiRequest);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not encode yaml", e);
}
ImmutableGcloudExtension config = getProject().getRootProject().getExtensions().getByType(GcloudExtension.class);
String command = config.download() ? CommandUtil.getGcloudSdkBinDir(getProject()).resolve("kubectl").toAbsolutePath().toString() : "kubectl";
getProject().exec(exec -> {
exec.executable(command);
exec.args("create", "-f", "-");
exec.setStandardInput(new ByteArrayInputStream(encodedApiRequest));
});
getProject().exec(exec -> {
exec.executable(command);
exec.args("certificate", "approve", cluster.namespace() + ".server.crt");
});
// Need to wait a bit for certificate to propagate before fetching.
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// Gradle Exec seems to be flaky when reading from stdout, so use normal ProcessBuilder.
final byte[] certificateBytes;
try {
Process getCertProcess = new ProcessBuilder(command, "get", "csr", cluster.namespace() + ".server.crt", "-o", "jsonpath={.status.certificate}").start();
certificateBytes = ByteStreams.toByteArray(getCertProcess.getInputStream());
} catch (IOException e) {
throw new UncheckedIOException("Could not fetch certificate.", e);
}
String certificate = new String(Base64.getDecoder().decode(certificateBytes), StandardCharsets.UTF_8);
final JcaPKCS8Generator keyGenerator;
final PemObject keyObject;
try {
keyGenerator = new JcaPKCS8Generator(keyPair.getPrivate(), null);
keyObject = keyGenerator.generate();
} catch (PemGenerationException e) {
throw new IllegalStateException("Could not encode to pkcs8.", e);
}
StringWriter keyWriter = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(keyWriter)) {
pemWriter.writeObject(keyObject);
} catch (IOException e) {
throw new IllegalStateException("Could not encode csr, can't happen.", e);
}
String key = keyWriter.toString();
KubernetesClient client = new DefaultKubernetesClient();
Secret certificateSecret = new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("server-tls").withNamespace(cluster.namespace()).build()).withType("Opaque").withData(ImmutableMap.of("server.crt", Base64.getEncoder().encodeToString(certificate.getBytes(StandardCharsets.UTF_8)), "server-key.pem", Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8)))).build();
client.resource(certificateSecret).createOrReplace();
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project nifi by apache.
the class CertificateUtils method generateSelfSignedX509Certificate.
/**
* Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
*
* @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for
* @param dn the distinguished name to user for the {@link X509Certificate}
* @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate}
* @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
* @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
* @throws CertificateException if there is an generating the new certificate
*/
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException {
try {
ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
// Set certificate extensions
// (1) digitalSignature extension
certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));
certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));
// (2) extendedKeyUsage extension
certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
// Sign the certificate
X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
} catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
throw new CertificateException(e);
}
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project nifi by apache.
the class OcspCertificateValidatorTest method generateIssuedCertificate.
/**
* Generates a certificate with a specific public key signed by the issuer key.
*
* @param dn the subject DN
* @param publicKey the subject public key
* @param issuerDn the issuer DN
* @param issuerKey the issuer private key
* @return the certificate
* @throws IOException if an exception occurs
* @throws NoSuchAlgorithmException if an exception occurs
* @throws CertificateException if an exception occurs
* @throws NoSuchProviderException if an exception occurs
* @throws SignatureException if an exception occurs
* @throws InvalidKeyException if an exception occurs
* @throws OperatorCreationException if an exception occurs
*/
private static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException {
ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey);
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
Date startDate = new Date(YESTERDAY);
Date endDate = new Date(ONE_YEAR_FROM_NOW);
X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(new X500Name(issuerDn), BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate, new X500Name(dn), subPubKeyInfo);
X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
return new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certificateHolder);
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project nifi by apache.
the class OcspCertificateValidatorTest method generateCertificate.
/**
* Generates a signed certificate with a specific keypair.
*
* @param dn the DN
* @param keyPair the public key will be included in the certificate and the the private key is used to sign the certificate
* @return the certificate
* @throws IOException if an exception occurs
* @throws NoSuchAlgorithmException if an exception occurs
* @throws CertificateException if an exception occurs
* @throws NoSuchProviderException if an exception occurs
* @throws SignatureException if an exception occurs
* @throws InvalidKeyException if an exception occurs
* @throws OperatorCreationException if an exception occurs
*/
private static X509Certificate generateCertificate(String dn, KeyPair keyPair) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException {
PrivateKey privateKey = keyPair.getPrivate();
ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(privateKey);
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
Date startDate = new Date(YESTERDAY);
Date endDate = new Date(ONE_YEAR_FROM_NOW);
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(new X500Name(dn), BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate, new X500Name(dn), subPubKeyInfo);
// Set certificate extensions
// (1) digitalSignature extension
certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement));
// (2) extendedKeyUsage extension
Vector<KeyPurposeId> ekUsages = new Vector<>();
ekUsages.add(KeyPurposeId.id_kp_clientAuth);
ekUsages.add(KeyPurposeId.id_kp_serverAuth);
certBuilder.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(ekUsages));
// Sign the certificate
X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
return new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certificateHolder);
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project ddf by codice.
the class LoginFilter method validateHolderOfKeyConfirmation.
private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs) throws SecurityServiceException {
List<String> confirmationMethods = assertion.getConfirmationMethods();
boolean hasHokMethod = false;
for (String method : confirmationMethods) {
if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
hasHokMethod = true;
}
}
if (hasHokMethod) {
if (x509Certs != null && x509Certs.length > 0) {
List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject().getSubjectConfirmations();
for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
Node keyInfo = dom.getFirstChild();
Node x509Data = keyInfo.getFirstChild();
Node dataNode = x509Data.getFirstChild();
Node dataText = dataNode.getFirstChild();
X509Certificate tlsCertificate = x509Certs[0];
if (dataNode.getLocalName().equals("X509Certificate")) {
String textContent = dataText.getTextContent();
byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(byteValue));
//check that the certificate is still valid
cert.checkValidity();
//if the certs aren't the same, verify
if (!tlsCertificate.equals(cert)) {
//verify that the cert was signed by the same private key as the TLS cert
cert.verify(tlsCertificate.getPublicKey());
}
} catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with certificate.");
}
} else if (dataNode.getLocalName().equals("X509SubjectName")) {
String textContent = dataText.getTextContent();
//If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject DN.");
}
} else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
//we have no way to support this confirmation type so we have to throw an error
throw new SecurityServiceException("Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
} else if (dataNode.getLocalName().equals("X509SKI")) {
String textContent = dataText.getTextContent();
byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
if (tlsSKI != null && tlsSKI.length > 0) {
ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(tlsOs.getOctets());
SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(assertionOs.getOctets());
//the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(), assertSubjectKeyIdentifier.getKeyIdentifier())) {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
}
} else {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
}
}
}
}
} else {
throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
}
}
}
Aggregations