Search in sources :

Example 21 with GeneralNames

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;
}
Also used : KeyPair(java.security.KeyPair) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateException(java.security.cert.CertificateException) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 22 with GeneralNames

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();
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509Extension(org.bouncycastle.asn1.x509.X509Extension) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) CRLReason(org.bouncycastle.asn1.x509.CRLReason) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) IOException(java.io.IOException) CRLException(java.security.cert.CRLException)

Example 23 with GeneralNames

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();
}
Also used : KeyPair(java.security.KeyPair) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) Extension(org.bouncycastle.asn1.x509.Extension) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) Security(java.security.Security) SecureRandom(java.security.SecureRandom) TaskAction(org.gradle.api.tasks.TaskAction) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) DefaultTask(org.gradle.api.DefaultTask) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KeyPairGenerator(java.security.KeyPairGenerator) PemObject(org.bouncycastle.util.io.pem.PemObject) ImmutableMap(com.google.common.collect.ImmutableMap) Streams(com.google.common.collect.Streams) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) Base64(java.util.Base64) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Stream(java.util.stream.Stream) GcloudExtension(org.curioswitch.gradle.plugins.gcloud.GcloudExtension) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteStreams(com.google.common.io.ByteStreams) Secret(io.fabric8.kubernetes.api.model.Secret) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) X500Principal(javax.security.auth.x500.X500Principal) PKCSObjectIdentifiers(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers) ContentSigner(org.bouncycastle.operator.ContentSigner) ImmutableGcloudExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableGcloudExtension) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ImmutableClusterExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableClusterExtension) ImmutableList(com.google.common.collect.ImmutableList) ClusterExtension(org.curioswitch.gradle.plugins.gcloud.ClusterExtension) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) StringWriter(java.io.StringWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) TimeUnit(java.util.concurrent.TimeUnit) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) CommandUtil(org.curioswitch.gradle.plugins.shared.CommandUtil) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) JcaPKCS8Generator(org.bouncycastle.openssl.jcajce.JcaPKCS8Generator) NoSuchProviderException(java.security.NoSuchProviderException) ImmutableGcloudExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableGcloudExtension) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) UncheckedIOException(java.io.UncheckedIOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ImmutableClusterExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableClusterExtension) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) StringWriter(java.io.StringWriter) JcaPKCS8Generator(org.bouncycastle.openssl.jcajce.JcaPKCS8Generator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) KeyPairGenerator(java.security.KeyPairGenerator) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) Secret(io.fabric8.kubernetes.api.model.Secret) PemObject(org.bouncycastle.util.io.pem.PemObject) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) ByteArrayInputStream(java.io.ByteArrayInputStream) X500Principal(javax.security.auth.x500.X500Principal) PemObject(org.bouncycastle.util.io.pem.PemObject) GeneralName(org.bouncycastle.asn1.x509.GeneralName) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) NoSuchProviderException(java.security.NoSuchProviderException) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) TaskAction(org.gradle.api.tasks.TaskAction)

Example 24 with GeneralNames

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();
}
Also used : GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) ArrayList(java.util.ArrayList) GeneralName(org.bouncycastle.asn1.x509.GeneralName) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Example 25 with GeneralNames

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>&gt;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;
}
Also used : GeneralNameInterface(sun.security.x509.GeneralNameInterface) GeneralNames(sun.security.x509.GeneralNames) SubjectAlternativeNameExtension(sun.security.x509.SubjectAlternativeNameExtension) X509CertImpl(sun.security.x509.X509CertImpl) GeneralSubtrees(sun.security.x509.GeneralSubtrees) IOException(java.io.IOException) X500Name(sun.security.x509.X500Name) NameConstraintsExtension(sun.security.x509.NameConstraintsExtension)

Aggregations

GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)72 GeneralName (org.bouncycastle.asn1.x509.GeneralName)58 IOException (java.io.IOException)31 X509Certificate (java.security.cert.X509Certificate)22 ArrayList (java.util.ArrayList)19 X500Name (org.bouncycastle.asn1.x500.X500Name)19 DERIA5String (org.bouncycastle.asn1.DERIA5String)14 Date (java.util.Date)13 List (java.util.List)13 DEROctetString (org.bouncycastle.asn1.DEROctetString)13 X500Principal (javax.security.auth.x500.X500Principal)12 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)12 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)12 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)12 GeneralNames (sun.security.x509.GeneralNames)12 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)11 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)11 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)11 Test (org.junit.Test)11 BigInteger (java.math.BigInteger)10