Search in sources :

Example 21 with CertificateExtensions

use of org.mozilla.jss.netscape.security.x509.CertificateExtensions 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 22 with CertificateExtensions

use of org.mozilla.jss.netscape.security.x509.CertificateExtensions in project candlepin by candlepin.

the class JSSPKIUtility method createX509Certificate.

@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions, Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair, BigInteger serialNumber, String alternateName) throws IOException {
    // Ensure JSS is properly initialized before attempting any operations with it
    JSSProviderLoader.initialize();
    X509CertInfo certInfo = new X509CertInfo();
    try {
        X509Certificate caCert = reader.getCACert();
        byte[] publicKeyEncoded = clientKeyPair.getPublic().getEncoded();
        certInfo.set(X509CertInfo.ISSUER, new CertificateIssuerName(new X500Name(caCert.getSubjectX500Principal().getEncoded())));
        certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(serialNumber));
        certInfo.set(X509CertInfo.VALIDITY, new CertificateValidity(startDate, endDate));
        certInfo.set(X509CertInfo.SUBJECT, new CertificateSubjectName(new X500Name(dn)));
        certInfo.set(X509CertInfo.KEY, new CertificateX509Key(X509Key.parse(new DerValue(publicKeyEncoded))));
        certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get(SIGNING_ALG_ID)));
        certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
        CertificateExtensions certExtensions = buildStandardExtensions(new CertificateExtensions(), dn, clientKeyPair, extensions, caCert, alternateName);
        certInfo.set(X509CertInfo.EXTENSIONS, certExtensions);
        if (extensions != null) {
            for (X509ExtensionWrapper wrapper : extensions) {
                // Avoid null values. Set them to blank if they are null
                String value = wrapper.getValue() == null ? "" : wrapper.getValue();
                UTF8String der = new UTF8String(value);
                certExtensions.add(buildCustomExtension(wrapper.getOid(), wrapper.isCritical(), der));
            }
        }
        if (byteExtensions != null) {
            for (X509ByteExtensionWrapper wrapper : byteExtensions) {
                // Avoid null values. Set them to blank if they are null
                byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
                OCTET_STRING der = new OCTET_STRING(value);
                certExtensions.add(buildCustomExtension(wrapper.getOid(), wrapper.isCritical(), der));
            }
        }
        X509CertImpl certImpl = new X509CertImpl(certInfo);
        certImpl.sign(reader.getCaKey(), SIGNING_ALG_ID);
        // valid, it just won't have any extensions present in the object.
        return new X509CertImpl(certImpl.getEncoded());
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("Could not create X.509 certificate", e);
    }
}
Also used : CertificateSubjectName(org.mozilla.jss.netscape.security.x509.CertificateSubjectName) UTF8String(org.mozilla.jss.asn1.UTF8String) X509CertInfo(org.mozilla.jss.netscape.security.x509.X509CertInfo) CertificateIssuerName(org.mozilla.jss.netscape.security.x509.CertificateIssuerName) GeneralSecurityException(java.security.GeneralSecurityException) CertificateVersion(org.mozilla.jss.netscape.security.x509.CertificateVersion) CertificateValidity(org.mozilla.jss.netscape.security.x509.CertificateValidity) CertificateExtensions(org.mozilla.jss.netscape.security.x509.CertificateExtensions) X500Name(org.mozilla.jss.netscape.security.x509.X500Name) UTF8String(org.mozilla.jss.asn1.UTF8String) CertificateX509Key(org.mozilla.jss.netscape.security.x509.CertificateX509Key) X509Certificate(java.security.cert.X509Certificate) CertificateSerialNumber(org.mozilla.jss.netscape.security.x509.CertificateSerialNumber) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) TokenRuntimeException(org.mozilla.jss.crypto.TokenRuntimeException) DerValue(org.mozilla.jss.netscape.security.util.DerValue) X509CertImpl(org.mozilla.jss.netscape.security.x509.X509CertImpl) X509ByteExtensionWrapper(org.candlepin.pki.X509ByteExtensionWrapper) X509ExtensionWrapper(org.candlepin.pki.X509ExtensionWrapper) CertificateAlgorithmId(org.mozilla.jss.netscape.security.x509.CertificateAlgorithmId)

Example 23 with CertificateExtensions

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

the class PKCS9Attribute method derEncode.

/**
 * Write the DER encoding of this attribute to an output stream.
 *
 * <P> N.B.: This method always encodes values of
 * ChallengePassword and UnstructuredAddress attributes as ASN.1
 * <code>PrintableString</code>s, without checking whether they
 * should be encoded as <code>T61String</code>s.
 */
public void derEncode(OutputStream out) throws IOException {
    DerOutputStream temp = new DerOutputStream();
    temp.putOID(oid);
    switch(index) {
        case // Unknown
        -1:
            temp.write((byte[]) value);
            break;
        // email address
        case 1:
        case // unstructured name
        2:
            {
                // open scope
                String[] values = (String[]) value;
                DerOutputStream[] temps = new DerOutputStream[values.length];
                for (int i = 0; i < values.length; i++) {
                    temps[i] = new DerOutputStream();
                    temps[i].putIA5String(values[i]);
                }
                temp.putOrderedSetOf(DerValue.tag_Set, temps);
            }
            // close scope
            break;
        case // content type
        3:
            {
                DerOutputStream temp2 = new DerOutputStream();
                temp2.putOID((ObjectIdentifier) value);
                temp.write(DerValue.tag_Set, temp2.toByteArray());
            }
            break;
        case // message digest
        4:
            {
                DerOutputStream temp2 = new DerOutputStream();
                temp2.putOctetString((byte[]) value);
                temp.write(DerValue.tag_Set, temp2.toByteArray());
            }
            break;
        case // signing time
        5:
            {
                DerOutputStream temp2 = new DerOutputStream();
                temp2.putUTCTime((Date) value);
                temp.write(DerValue.tag_Set, temp2.toByteArray());
            }
            break;
        case // countersignature
        6:
            temp.putOrderedSetOf(DerValue.tag_Set, (DerEncoder[]) value);
            break;
        case // challenge password
        7:
            {
                DerOutputStream temp2 = new DerOutputStream();
                temp2.putPrintableString((String) value);
                temp.write(DerValue.tag_Set, temp2.toByteArray());
            }
            break;
        case // unstructured address
        8:
            {
                // open scope
                String[] values = (String[]) value;
                DerOutputStream[] temps = new DerOutputStream[values.length];
                for (int i = 0; i < values.length; i++) {
                    temps[i] = new DerOutputStream();
                    temps[i].putPrintableString(values[i]);
                }
                temp.putOrderedSetOf(DerValue.tag_Set, temps);
            }
            // close scope
            break;
        case // extended-certificate attribute -- not supported
        9:
            throw new IOException("PKCS9 extended-certificate " + "attribute not supported.");
        // break unnecessary
        case // issuerAndserialNumber attribute -- not supported
        10:
            throw new IOException("PKCS9 IssuerAndSerialNumber" + "attribute not supported.");
        // RSA DSI proprietary
        case 11:
        case // RSA DSI proprietary
        12:
            throw new IOException("PKCS9 RSA DSI attributes" + "11 and 12, not supported.");
        // break unnecessary
        case // S/MIME unused attribute
        13:
            throw new IOException("PKCS9 attribute #13 not supported.");
        case // ExtensionRequest
        14:
            {
                DerOutputStream temp2 = new DerOutputStream();
                CertificateExtensions exts = (CertificateExtensions) value;
                try {
                    exts.encode(temp2, true);
                } catch (CertificateException ex) {
                    throw new IOException(ex.toString());
                }
                temp.write(DerValue.tag_Set, temp2.toByteArray());
            }
            break;
        case // SMIMECapability
        15:
            throw new IOException("PKCS9 attribute #15 not supported.");
        case // SigningCertificate
        16:
            throw new IOException("PKCS9 SigningCertificate attribute not supported.");
        case // SignatureTimestampToken
        17:
            temp.write(DerValue.tag_Set, (byte[]) value);
            break;
        // can't happen
        default:
    }
    DerOutputStream derOut = new DerOutputStream();
    derOut.write(DerValue.tag_Sequence, temp.toByteArray());
    out.write(derOut.toByteArray());
}
Also used : DerOutputStream(sun.security.util.DerOutputStream) DerEncoder(sun.security.util.DerEncoder) CertificateExtensions(sun.security.x509.CertificateExtensions) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) Date(java.util.Date) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Example 24 with CertificateExtensions

use of org.mozilla.jss.netscape.security.x509.CertificateExtensions 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 25 with CertificateExtensions

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

the class X509Generator method updateWithRootCertificateExtensions.

private void updateWithRootCertificateExtensions(final X509CertInfo x509CertInfo, final PublicKey publicKey) throws IOException, CertificateException {
    CertificateExtensions certificateExtensions = new CertificateExtensions();
    // See: https://tools.ietf.org/html/rfc5280#section-4.2.1.9
    certificateExtensions.set(BasicConstraintsExtension.NAME, new BasicConstraintsExtension(// is critical
    true, // is CA
    true, // path length
    -1));
    // See: https://tools.ietf.org/html/rfc5280#section-4.2.1.3
    boolean[] keyUsage = new boolean[9];
    // keyCertSign
    keyUsage[5] = true;
    certificateExtensions.set(KeyUsageExtension.NAME, new KeyUsageExtension(keyUsage));
    // See: https://tools.ietf.org/html/rfc5280#section-4.2.1.2
    certificateExtensions.set(SubjectKeyIdentifierExtension.NAME, new SubjectKeyIdentifierExtension(new KeyIdentifier(publicKey).getIdentifier()));
    x509CertInfo.set(X509CertInfo.EXTENSIONS, certificateExtensions);
}
Also used : SubjectKeyIdentifierExtension(sun.security.x509.SubjectKeyIdentifierExtension) BasicConstraintsExtension(sun.security.x509.BasicConstraintsExtension) KeyIdentifier(sun.security.x509.KeyIdentifier) CertificateExtensions(sun.security.x509.CertificateExtensions) KeyUsageExtension(sun.security.x509.KeyUsageExtension)

Aggregations

CertificateExtensions (sun.security.x509.CertificateExtensions)21 KeyUsageExtension (sun.security.x509.KeyUsageExtension)9 IOException (java.io.IOException)8 Date (java.util.Date)8 ExtendedKeyUsageExtension (sun.security.x509.ExtendedKeyUsageExtension)8 SubjectAlternativeNameExtension (sun.security.x509.SubjectAlternativeNameExtension)7 CertificateException (java.security.cert.CertificateException)6 GeneralName (sun.security.x509.GeneralName)6 GeneralNames (sun.security.x509.GeneralNames)6 X509CertImpl (sun.security.x509.X509CertImpl)6 X509CertInfo (sun.security.x509.X509CertInfo)6 CertificateExtensions (org.mozilla.jss.netscape.security.x509.CertificateExtensions)5 ObjectIdentifier (sun.security.util.ObjectIdentifier)4 X500Name (sun.security.x509.X500Name)4 BigInteger (java.math.BigInteger)3 SecureRandom (java.security.SecureRandom)3 X509Certificate (java.security.cert.X509Certificate)3 ObjectIdentifier (org.mozilla.jss.netscape.security.util.ObjectIdentifier)3 CertificateX509Key (org.mozilla.jss.netscape.security.x509.CertificateX509Key)3 X509CertInfo (org.mozilla.jss.netscape.security.x509.X509CertInfo)3