Search in sources :

Example 11 with SubjectAlternativeNameExtension

use of org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension in project OpenAM by OpenRock.

the class ApprovalCallback method approve.

/*
    * Invoked by JSS protocol handler whenever ssl handshaking hits issue.
    * It validates reported issue if it can be ignored.
    *
    * @return <code>true</code> if the reported issue can be ignored.
    */
public boolean approve(X509Certificate cert, SSLCertificateApprovalCallback.ValidityStatus status) {
    ValidityItem item;
    Enumeration errors = status.getReasons();
    int reason;
    if (trustAllServerCerts) {
        return true;
    }
    if ((reqHost == null) && !errors.hasMoreElements()) {
        return true;
    }
    boolean approve = true;
    while (approve && errors.hasMoreElements()) {
        item = (SSLCertificateApprovalCallback.ValidityItem) errors.nextElement();
        reason = item.getReason();
        if (debug.messageEnabled()) {
            debug.message("ApprovalCallback: reason " + reason);
        }
        // bad domain -12276
        if (reason != ValidityStatus.BAD_CERT_DOMAIN) {
            approve = false;
        } else {
            String cn = null;
            try {
                String subjectDN = cert.getSubjectDN().getName();
                cn = new X500Name(subjectDN).getCommonName();
            } catch (Exception ex) {
                if (debug.messageEnabled()) {
                    debug.message("ApprovalCallback:", ex);
                }
                approve = false;
            }
            if (cn == null) {
                return false;
            }
            if (!sslTrustHosts.isEmpty()) {
                if (debug.messageEnabled()) {
                    debug.message("ApprovalCallback: server cert CN : " + cn);
                }
                if (sslTrustHosts.contains(cn.toLowerCase())) {
                    return true;
                }
            }
            if (resolveIPAddress) {
                try {
                    approve = InetAddress.getByName(cn).getHostAddress().equals(InetAddress.getByName(reqHost).getHostAddress());
                } catch (UnknownHostException ex) {
                    if (debug.messageEnabled()) {
                        debug.message("ApprovalCallback:", ex);
                    }
                    approve = false;
                }
            } else
                approve = false;
            if (!approve && checkSubjectAltName) {
                try {
                    X509CertImpl certImpl = new X509CertImpl(cert.getEncoded());
                    X509CertInfo cinfo = new X509CertInfo(certImpl.getTBSCertificate());
                    CertificateExtensions exts = (CertificateExtensions) cinfo.get(X509CertInfo.EXTENSIONS);
                    SubjectAlternativeNameExtension altNameExt = (SubjectAlternativeNameExtension) exts.get(SubjectAlternativeNameExtension.NAME);
                    if (altNameExt != null) {
                        GeneralNames names = (GeneralNames) altNameExt.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
                        Method meth = getMethod();
                        GeneralName generalname = null;
                        if (meth.getName().equals(OLD_METHOD_NAME)) {
                            // pre 1.4.2 implementation
                            Enumeration e = (Enumeration) meth.invoke(names, params);
                            for (; !approve && e.hasMoreElements(); ) {
                                approve = compareHosts((GeneralName) e.nextElement());
                            }
                        } else {
                            // post 1.4.2 implementation
                            Iterator i = (Iterator) meth.invoke(names, params);
                            for (; !approve && i.hasNext(); ) {
                                approve = compareHosts((GeneralName) i.next());
                            }
                        }
                    }
                } catch (Exception ex) {
                    return false;
                }
            }
        }
    }
    return approve;
}
Also used : Enumeration(java.util.Enumeration) UnknownHostException(java.net.UnknownHostException) X509CertInfo(sun.security.x509.X509CertInfo) SubjectAlternativeNameExtension(sun.security.x509.SubjectAlternativeNameExtension) CertificateExtensions(sun.security.x509.CertificateExtensions) X500Name(sun.security.x509.X500Name) Method(java.lang.reflect.Method) UnknownHostException(java.net.UnknownHostException) SSLCertificateApprovalCallback(org.mozilla.jss.ssl.SSLCertificateApprovalCallback) GeneralNames(sun.security.x509.GeneralNames) X509CertImpl(sun.security.x509.X509CertImpl) Iterator(java.util.Iterator) GeneralName(sun.security.x509.GeneralName)

Example 12 with SubjectAlternativeNameExtension

use of org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension in project j2objc by google.

the class ForwardState method updateState.

/**
 * Update the state with the next certificate added to the path.
 *
 * @param cert the certificate which is used to update the state
 */
@Override
public void updateState(X509Certificate cert) throws CertificateException, IOException, CertPathValidatorException {
    if (cert == null)
        return;
    X509CertImpl icert = X509CertImpl.toImpl(cert);
    /* see if certificate key has null parameters */
    if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
        keyParamsNeededFlag = true;
    }
    /* update certificate */
    this.cert = icert;
    /* update issuer DN */
    issuerDN = cert.getIssuerX500Principal();
    if (!X509CertImpl.isSelfIssued(cert)) {
        /*
             * update traversedCACerts only if this is a non-self-issued
             * intermediate CA cert
             */
        if (!init && cert.getBasicConstraints() != -1) {
            traversedCACerts++;
        }
    }
    /* update subjectNamesTraversed only if this is the EE cert or if
           this cert is not self-issued */
    if (init || !X509CertImpl.isSelfIssued(cert)) {
        X500Principal subjName = cert.getSubjectX500Principal();
        subjectNamesTraversed.add(X500Name.asX500Name(subjName));
        try {
            SubjectAlternativeNameExtension subjAltNameExt = icert.getSubjectAlternativeNameExtension();
            if (subjAltNameExt != null) {
                GeneralNames gNames = subjAltNameExt.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
                for (GeneralName gName : gNames.names()) {
                    subjectNamesTraversed.add(gName.getName());
                }
            }
        } catch (IOException e) {
            if (debug != null) {
                debug.println("ForwardState.updateState() unexpected " + "exception");
                e.printStackTrace();
            }
            throw new CertPathValidatorException(e);
        }
    }
    init = false;
}
Also used : CertPathValidatorException(java.security.cert.CertPathValidatorException) GeneralNames(sun.security.x509.GeneralNames) SubjectAlternativeNameExtension(sun.security.x509.SubjectAlternativeNameExtension) X509CertImpl(sun.security.x509.X509CertImpl) X500Principal(javax.security.auth.x500.X500Principal) GeneralName(sun.security.x509.GeneralName) IOException(java.io.IOException)

Example 13 with SubjectAlternativeNameExtension

use of org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension in project j2objc by google.

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)

Example 14 with SubjectAlternativeNameExtension

use of org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension in project mockserver by mock-server.

the class X509Generator method updateWithCertificateExtensions.

private void updateWithCertificateExtensions(final X509CertInfo x509CertInfo, final PublicKey publicKey, final PublicKey caPublicKey, final Set<String> subjectAlternativeNames) throws IOException, CertificateException {
    CertificateExtensions certificateExtensions = new CertificateExtensions();
    GeneralNames generalNames = subjectAlternativeNames.stream().filter(StringUtils::isNotBlank).map(this::buildGeneralName).filter(Objects::nonNull).collect(Collector.of(GeneralNames::new, GeneralNames::add, // do nothing
    (generalNames1, generalNames2) -> null));
    if (!generalNames.isEmpty()) {
        certificateExtensions.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(Boolean.FALSE, generalNames));
    }
    // See: https://tools.ietf.org/html/rfc5280#section-4.2.1.2
    certificateExtensions.set(SubjectKeyIdentifierExtension.NAME, new SubjectKeyIdentifierExtension(new KeyIdentifier(publicKey).getIdentifier()));
    // See: https://tools.ietf.org/html/rfc5280#section-4.2.1.2
    certificateExtensions.set(AuthorityKeyIdentifierExtension.NAME, new AuthorityKeyIdentifierExtension(new KeyIdentifier(caPublicKey), null, null));
    // See: https://tools.ietf.org/html/rfc5280#section-4.2.1.1
    x509CertInfo.set(X509CertInfo.EXTENSIONS, certificateExtensions);
}
Also used : CertificateValidity(sun.security.x509.CertificateValidity) X509Certificate(java.security.cert.X509Certificate) java.util(java.util) InternetDomainName(com.google.common.net.InternetDomainName) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SubjectAlternativeNameExtension(sun.security.x509.SubjectAlternativeNameExtension) CertificateSerialNumber(sun.security.x509.CertificateSerialNumber) StringUtils(org.apache.commons.lang3.StringUtils) GeneralName(sun.security.x509.GeneralName) IPAddressName(sun.security.x509.IPAddressName) X500Name(sun.security.x509.X500Name) Level(org.slf4j.event.Level) CertificateExtensions(sun.security.x509.CertificateExtensions) BigInteger(java.math.BigInteger) SubjectKeyIdentifierExtension(sun.security.x509.SubjectKeyIdentifierExtension) Collector(java.util.stream.Collector) BasicConstraintsExtension(sun.security.x509.BasicConstraintsExtension) DerValue(sun.security.util.DerValue) KeyUsageExtension(sun.security.x509.KeyUsageExtension) java.security(java.security) KeyIdentifier(sun.security.x509.KeyIdentifier) AuthorityKeyIdentifierExtension(sun.security.x509.AuthorityKeyIdentifierExtension) CertificateSigningRequest(org.mockserver.socket.tls.jdk.CertificateSigningRequest) IOException(java.io.IOException) DNSName(sun.security.x509.DNSName) CertificateException(java.security.cert.CertificateException) X509CertImpl(sun.security.x509.X509CertImpl) CertificateAlgorithmId(sun.security.x509.CertificateAlgorithmId) CertificateX509Key(sun.security.x509.CertificateX509Key) PEMToFile(org.mockserver.socket.tls.PEMToFile) LogEntry(org.mockserver.log.model.LogEntry) CertificateVersion(sun.security.x509.CertificateVersion) MockServerLogger(org.mockserver.logging.MockServerLogger) InetAddresses(com.google.common.net.InetAddresses) GeneralNames(sun.security.x509.GeneralNames) AlgorithmId(sun.security.x509.AlgorithmId) X509CertInfo(sun.security.x509.X509CertInfo) SubjectKeyIdentifierExtension(sun.security.x509.SubjectKeyIdentifierExtension) GeneralNames(sun.security.x509.GeneralNames) KeyIdentifier(sun.security.x509.KeyIdentifier) SubjectAlternativeNameExtension(sun.security.x509.SubjectAlternativeNameExtension) AuthorityKeyIdentifierExtension(sun.security.x509.AuthorityKeyIdentifierExtension) CertificateExtensions(sun.security.x509.CertificateExtensions)

Example 15 with SubjectAlternativeNameExtension

use of org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension in project jss by dogtagpki.

the class ExtPrettyPrint method getSubjectAlternativeNameExtension.

/**
 * String Representation of SubjectAlternativeName Extension
 */
private String getSubjectAlternativeNameExtension() {
    StringBuffer sb = new StringBuffer();
    try {
        sb.append(pp.indent(mIndentSize) + mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
        sb.append(mResource.getString(PrettyPrintResources.TOKEN_SUBJECT_ALT_NAME) + "- " + mExt.getExtensionId().toString() + "\n");
        sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
        SubjectAlternativeNameExtension ext = (SubjectAlternativeNameExtension) mExt;
        if (mExt.isCritical()) {
            sb.append(mResource.getString(PrettyPrintResources.TOKEN_YES) + "\n");
        } else {
            sb.append(mResource.getString(PrettyPrintResources.TOKEN_NO) + "\n");
        }
        GeneralNames subjectNames = (GeneralNames) ext.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
        sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_VALUE) + "\n");
        for (int i = 0; i < subjectNames.size(); i++) {
            GeneralName subjectName = (GeneralName) subjectNames.elementAt(i);
            if (subjectName != null) {
                String nameType = "";
                if (subjectName.getType() == GeneralNameInterface.NAME_DIRECTORY)
                    nameType = "DirectoryName: ";
                sb.append(pp.indent(mIndentSize + 8) + nameType + subjectName.toString() + "\n");
            }
        }
        return sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
Also used : GeneralNames(org.mozilla.jss.netscape.security.x509.GeneralNames) SubjectAlternativeNameExtension(org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension) GeneralName(org.mozilla.jss.netscape.security.x509.GeneralName) IOException(java.io.IOException) CRLDistributionPoint(org.mozilla.jss.netscape.security.x509.CRLDistributionPoint) IssuingDistributionPoint(org.mozilla.jss.netscape.security.x509.IssuingDistributionPoint)

Aggregations

SubjectAlternativeNameExtension (sun.security.x509.SubjectAlternativeNameExtension)14 GeneralNames (sun.security.x509.GeneralNames)13 IOException (java.io.IOException)10 GeneralName (sun.security.x509.GeneralName)10 X509CertImpl (sun.security.x509.X509CertImpl)10 CertificateExtensions (sun.security.x509.CertificateExtensions)7 X500Name (sun.security.x509.X500Name)6 DNSName (sun.security.x509.DNSName)4 X509CertInfo (sun.security.x509.X509CertInfo)4 CertPathValidatorException (java.security.cert.CertPathValidatorException)3 X500Principal (javax.security.auth.x500.X500Principal)3 GeneralNameInterface (sun.security.x509.GeneralNameInterface)3 IPAddressName (sun.security.x509.IPAddressName)3 BigInteger (java.math.BigInteger)2 PrivateKey (java.security.PrivateKey)2 CertificateException (java.security.cert.CertificateException)2 X509Certificate (java.security.cert.X509Certificate)2 Date (java.util.Date)2 Iterator (java.util.Iterator)2 GeneralName (org.mozilla.jss.netscape.security.x509.GeneralName)2