use of de.carne.certmgr.certs.x509.GeneralNames in project zaproxy by zaproxy.
the class SslCertificateServiceImpl method createCertForHost.
@Override
public KeyStore createCertForHost(String hostname) throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException, KeyStoreException, IOException, UnrecoverableKeyException {
if (hostname == null) {
throw new IllegalArgumentException("Error, 'hostname' is not allowed to be null!");
}
if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) {
throw new MissingRootCertificateException(this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one.");
}
final KeyPair mykp = this.createKeyPair();
final PrivateKey privKey = mykp.getPrivate();
final PublicKey pubKey = mykp.getPublic();
X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
namebld.addRDN(BCStyle.CN, hostname);
namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project");
namebld.addRDN(BCStyle.O, "OWASP");
namebld.addRDN(BCStyle.C, "xx");
namebld.addRDN(BCStyle.EmailAddress, "owasp-zed-attack-proxy@lists.owasp.org");
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(new X509CertificateHolder(caCert.getEncoded()).getSubject(), BigInteger.valueOf(serial.getAndIncrement()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + 100 * (1000L * 60 * 60 * 24 * 30)), namebld.build(), pubKey);
certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
certGen.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.dNSName, hostname)));
ContentSigner sigGen;
try {
sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caPrivKey);
} catch (OperatorCreationException e) {
throw new CertificateException(e);
}
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
cert.checkValidity(new Date());
cert.verify(caPubKey);
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
final Certificate[] chain = new Certificate[2];
chain[1] = this.caCert;
chain[0] = cert;
ks.setKeyEntry(ZAPROXY_JKS_ALIAS, privKey, PASSPHRASE, chain);
return ks;
}
use of de.carne.certmgr.certs.x509.GeneralNames in project XobotOS by xamarin.
the class X509CRLEntryObject method toString.
public String toString() {
StringBuffer buf = new StringBuffer();
String nl = System.getProperty("line.separator");
buf.append(" userCertificate: ").append(this.getSerialNumber()).append(nl);
buf.append(" revocationDate: ").append(this.getRevocationDate()).append(nl);
buf.append(" certificateIssuer: ").append(this.getCertificateIssuer()).append(nl);
X509Extensions extensions = c.getExtensions();
if (extensions != null) {
Enumeration e = extensions.oids();
if (e.hasMoreElements()) {
buf.append(" crlEntryExtensions:").append(nl);
while (e.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
X509Extension ext = extensions.getExtension(oid);
if (ext.getValue() != null) {
byte[] octs = ext.getValue().getOctets();
ASN1InputStream dIn = new ASN1InputStream(octs);
buf.append(" critical(").append(ext.isCritical()).append(") ");
try {
if (oid.equals(X509Extensions.ReasonCode)) {
buf.append(new CRLReason(DEREnumerated.getInstance(dIn.readObject()))).append(nl);
} else if (oid.equals(X509Extensions.CertificateIssuer)) {
buf.append("Certificate issuer: ").append(new GeneralNames((ASN1Sequence) dIn.readObject())).append(nl);
} else {
buf.append(oid.getId());
buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
}
} catch (Exception ex) {
buf.append(oid.getId());
buf.append(" value = ").append("*****").append(nl);
}
} else {
buf.append(nl);
}
}
}
}
return buf.toString();
}
use of de.carne.certmgr.certs.x509.GeneralNames 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 de.carne.certmgr.certs.x509.GeneralNames in project nifi by apache.
the class TlsHelper method createDomainAlternativeNamesExtensions.
public static Extensions createDomainAlternativeNamesExtensions(String domainAlternativeNames, String requestedDn) throws IOException {
List<GeneralName> namesList = new ArrayList<>();
try {
final String cn = IETFUtils.valueToString(new X500Name(requestedDn).getRDNs(BCStyle.CN)[0].getFirst().getValue());
namesList.add(new GeneralName(GeneralName.dNSName, cn));
} catch (Exception e) {
throw new IOException("Failed to extract CN from request DN: " + requestedDn, e);
}
if (StringUtils.isNotBlank(domainAlternativeNames)) {
for (String alternativeName : domainAlternativeNames.split(",")) {
namesList.add(new GeneralName(GeneralName.dNSName, alternativeName));
}
}
GeneralNames subjectAltNames = new GeneralNames(namesList.toArray(new GeneralName[] {}));
ExtensionsGenerator extGen = new ExtensionsGenerator();
extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
return extGen.generate();
}
use of de.carne.certmgr.certs.x509.GeneralNames in project jdk8u_jdk by JetBrains.
the class Builder method targetDistance.
/**
* Determine how close a given certificate gets you toward
* a given target.
*
* @param constraints Current NameConstraints; if null,
* then caller must verify NameConstraints
* independently, realizing that this certificate
* may not actually lead to the target at all.
* @param cert Candidate certificate for chain
* @param target GeneralNameInterface name of target
* @return distance from this certificate to target:
* <ul>
* <li>-1 means certificate could be CA for target, but
* there are no NameConstraints limiting how close
* <li> 0 means certificate subject or subjectAltName
* matches target
* <li> 1 means certificate is permitted to be CA for
* target.
* <li> 2 means certificate is permitted to be CA for
* parent of target.
* <li>>0 in general, means certificate is permitted
* to be a CA for this distance higher in the naming
* hierarchy than the target, plus 1.
* </ul>
* <p>Note that the subject and/or subjectAltName of the
* candidate cert does not have to be an ancestor of the
* target in order to be a CA that can issue a certificate to
* the target. In these cases, the target distance is calculated
* by inspecting the NameConstraints extension in the candidate
* certificate. For example, suppose the target is an X.500 DN with
* a value of "CN=mullan,OU=ireland,O=sun,C=us" and the
* NameConstraints extension in the candidate certificate
* includes a permitted component of "O=sun,C=us", which implies
* that the candidate certificate is allowed to issue certs in
* the "O=sun,C=us" namespace. The target distance is 3
* ((distance of permitted NC from target) + 1).
* The (+1) is added to distinguish the result from the case
* which returns (0).
* @throws IOException if certificate does not get closer
*/
static int targetDistance(NameConstraintsExtension constraints, X509Certificate cert, GeneralNameInterface target) throws IOException {
/* ensure that certificate satisfies existing name constraints */
if (constraints != null && !constraints.verify(cert)) {
throw new IOException("certificate does not satisfy existing name " + "constraints");
}
X509CertImpl certImpl;
try {
certImpl = X509CertImpl.toImpl(cert);
} catch (CertificateException e) {
throw new IOException("Invalid certificate", e);
}
/* see if certificate subject matches target */
X500Name subject = X500Name.asX500Name(certImpl.getSubjectX500Principal());
if (subject.equals(target)) {
/* match! */
return 0;
}
SubjectAlternativeNameExtension altNameExt = certImpl.getSubjectAlternativeNameExtension();
if (altNameExt != null) {
GeneralNames altNames = altNameExt.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
/* see if any alternative name matches target */
if (altNames != null) {
for (int j = 0, n = altNames.size(); j < n; j++) {
GeneralNameInterface altName = altNames.get(j).getName();
if (altName.equals(target)) {
return 0;
}
}
}
}
/* no exact match; see if certificate can get us to target */
/* first, get NameConstraints out of certificate */
NameConstraintsExtension ncExt = certImpl.getNameConstraintsExtension();
if (ncExt == null) {
return -1;
}
/* merge certificate's NameConstraints with current NameConstraints */
if (constraints != null) {
constraints.merge(ncExt);
} else {
// Make sure we do a clone here, because we're probably
// going to modify this object later and we don't want to
// be sharing it with a Certificate object!
constraints = (NameConstraintsExtension) ncExt.clone();
}
if (debug != null) {
debug.println("Builder.targetDistance() merged constraints: " + String.valueOf(constraints));
}
/* reduce permitted by excluded */
GeneralSubtrees permitted = constraints.get(NameConstraintsExtension.PERMITTED_SUBTREES);
GeneralSubtrees excluded = constraints.get(NameConstraintsExtension.EXCLUDED_SUBTREES);
if (permitted != null) {
permitted.reduce(excluded);
}
if (debug != null) {
debug.println("Builder.targetDistance() reduced constraints: " + permitted);
}
/* see if new merged constraints allow target */
if (!constraints.verify(target)) {
throw new IOException("New certificate not allowed to sign " + "certificate for target");
}
/* find distance to target, if any, in permitted */
if (permitted == null) {
/* certificate is unconstrained; could sign for anything */
return -1;
}
for (int i = 0, n = permitted.size(); i < n; i++) {
GeneralNameInterface perName = permitted.get(i).getName().getName();
int distance = distance(perName, target, -1);
if (distance >= 0) {
return (distance + 1);
}
}
/* no matching type in permitted; cert holder could certify target */
return -1;
}
Aggregations