Example usage for java.security.cert X509Certificate checkValidity

List of usage examples for java.security.cert X509Certificate checkValidity

Introduction

In this page you can find the example usage for java.security.cert X509Certificate checkValidity.

Prototype

public abstract void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException;

Source Link

Document

Checks that the certificate is currently valid.

Usage

From source file:android.net.http.CertificateChainValidator.java

/**
 * Performs the handshake and server certificates validation
 * @param sslSocket The secure connection socket
 * @param domain The website domain// w  w w . j ava 2 s  .c o  m
 * @return An SSL error object if there is an error and null otherwise
 */
public SslError doHandshakeAndValidateServerCertificates(HttpsConnection connection, SSLSocket sslSocket,
        String domain) throws SSLHandshakeException, IOException {

    ++sTotal;

    SSLContext sslContext = HttpsConnection.getContext();
    if (sslContext == null) {
        closeSocketThrowException(sslSocket, "SSL context is null");
    }

    X509Certificate[] serverCertificates = null;

    long sessionBeforeHandshakeLastAccessedTime = 0;
    byte[] sessionBeforeHandshakeId = null;

    SSLSession sessionAfterHandshake = null;

    synchronized (sslContext) {
        // get SSL session before the handshake
        SSLSession sessionBeforeHandshake = getSSLSession(sslContext, connection.getHost());
        if (sessionBeforeHandshake != null) {
            sessionBeforeHandshakeLastAccessedTime = sessionBeforeHandshake.getLastAccessedTime();

            sessionBeforeHandshakeId = sessionBeforeHandshake.getId();
        }

        // start handshake, close the socket if we fail
        try {
            sslSocket.setUseClientMode(true);
            sslSocket.startHandshake();
        } catch (IOException e) {
            closeSocketThrowException(sslSocket, e.getMessage(), "failed to perform SSL handshake");
        }

        // retrieve the chain of the server peer certificates
        Certificate[] peerCertificates = sslSocket.getSession().getPeerCertificates();

        if (peerCertificates == null || peerCertificates.length <= 0) {
            closeSocketThrowException(sslSocket, "failed to retrieve peer certificates");
        } else {
            serverCertificates = new X509Certificate[peerCertificates.length];
            for (int i = 0; i < peerCertificates.length; ++i) {
                serverCertificates[i] = (X509Certificate) (peerCertificates[i]);
            }

            // update the SSL certificate associated with the connection
            if (connection != null) {
                if (serverCertificates[0] != null) {
                    connection.setCertificate(new SslCertificate(serverCertificates[0]));
                }
            }
        }

        // get SSL session after the handshake
        sessionAfterHandshake = getSSLSession(sslContext, connection.getHost());
    }

    if (sessionBeforeHandshakeLastAccessedTime != 0 && sessionAfterHandshake != null
            && Arrays.equals(sessionBeforeHandshakeId, sessionAfterHandshake.getId())
            && sessionBeforeHandshakeLastAccessedTime < sessionAfterHandshake.getLastAccessedTime()) {

        if (HttpLog.LOGV) {
            HttpLog.v("SSL session was reused: total reused: " + sTotalReused + " out of total of: " + sTotal);

            ++sTotalReused;
        }

        // no errors!!!
        return null;
    }

    // check if the first certificate in the chain is for this site
    X509Certificate currCertificate = serverCertificates[0];
    if (currCertificate == null) {
        closeSocketThrowException(sslSocket, "certificate for this site is null");
    } else {
        if (!DomainNameChecker.match(currCertificate, domain)) {
            String errorMessage = "certificate not for this host: " + domain;

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            sslSocket.getSession().invalidate();
            return new SslError(SslError.SSL_IDMISMATCH, currCertificate);
        }
    }

    //
    // first, we validate the chain using the standard validation
    // solution; if we do not find any errors, we are done; if we
    // fail the standard validation, we re-validate again below,
    // this time trying to retrieve any individual errors we can
    // report back to the user.
    //
    try {
        synchronized (mDefaultTrustManager) {
            mDefaultTrustManager.checkServerTrusted(serverCertificates, "RSA");

            // no errors!!!
            return null;
        }
    } catch (CertificateException e) {
        if (HttpLog.LOGV) {
            HttpLog.v("failed to pre-validate the certificate chain, error: " + e.getMessage());
        }
    }

    sslSocket.getSession().invalidate();

    SslError error = null;

    // we check the root certificate separately from the rest of the
    // chain; this is because we need to know what certificate in
    // the chain resulted in an error if any
    currCertificate = serverCertificates[serverCertificates.length - 1];
    if (currCertificate == null) {
        closeSocketThrowException(sslSocket, "root certificate is null");
    }

    // check if the last certificate in the chain (root) is trusted
    X509Certificate[] rootCertificateChain = { currCertificate };
    try {
        synchronized (mDefaultTrustManager) {
            mDefaultTrustManager.checkServerTrusted(rootCertificateChain, "RSA");
        }
    } catch (CertificateExpiredException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate has expired";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        error = new SslError(SslError.SSL_EXPIRED, currCertificate);
    } catch (CertificateNotYetValidException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate not valid yet";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        error = new SslError(SslError.SSL_NOTYETVALID, currCertificate);
    } catch (CertificateException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate not trusted";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
    }

    // Then go through the certificate chain checking that each
    // certificate trusts the next and that each certificate is
    // within its valid date range. Walk the chain in the order
    // from the CA to the end-user
    X509Certificate prevCertificate = serverCertificates[serverCertificates.length - 1];

    for (int i = serverCertificates.length - 2; i >= 0; --i) {
        currCertificate = serverCertificates[i];

        // if a certificate is null, we cannot verify the chain
        if (currCertificate == null) {
            closeSocketThrowException(sslSocket, "null certificate in the chain");
        }

        // verify if trusted by chain
        if (!prevCertificate.getSubjectDN().equals(currCertificate.getIssuerDN())) {
            String errorMessage = "not trusted by chain";

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
        }

        try {
            currCertificate.verify(prevCertificate.getPublicKey());
        } catch (GeneralSecurityException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "not trusted by chain";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
        }

        // verify if the dates are valid
        try {
            currCertificate.checkValidity();
        } catch (CertificateExpiredException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "certificate expired";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            if (error == null || error.getPrimaryError() < SslError.SSL_EXPIRED) {
                error = new SslError(SslError.SSL_EXPIRED, currCertificate);
            }
        } catch (CertificateNotYetValidException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "certificate not valid yet";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            if (error == null || error.getPrimaryError() < SslError.SSL_NOTYETVALID) {
                error = new SslError(SslError.SSL_NOTYETVALID, currCertificate);
            }
        }

        prevCertificate = currCertificate;
    }

    // if we do not have an error to report back to the user, throw
    // an exception (a generic error will be reported instead)
    if (error == null) {
        closeSocketThrowException(sslSocket,
                "failed to pre-validate the certificate chain due to a non-standard error");
    }

    return error;
}

From source file:org.dogtagpki.server.rest.UserService.java

/**
 * Adds a certificate to a user/*from w  w w.j  av  a 2 s.  c  om*/
 * <P>
 *
 * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/
 * ui/admin-protocol-definition.html#user-admin
 * <P>
 *
 * <ul>
 * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
 * users/groups)
 * </ul>
 */
@Override
public Response addUserCert(String userID, UserCertData userCertData) {

    if (userCertData == null)
        throw new BadRequestException("Certificate data is null.");

    // ensure that any low-level exceptions are reported
    // to the signed audit log and stored as failures
    try {
        if (userID == null) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
            throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
        }

        IUser user = userGroupManager.createUser(userID);

        String encoded = userCertData.getEncoded();

        // no cert is a success
        if (encoded == null) {
            auditAddUserCert(userID, userCertData, ILogger.SUCCESS);
            return createOKResponse();
        }

        // only one cert added per operation
        X509Certificate cert = null;

        // Base64 decode cert
        byte binaryCert[] = Cert.parseCertificate(encoded);

        try {
            cert = new X509CertImpl(binaryCert);

        } catch (CertificateException e) {
            CMS.debug("UserService: Submitted data is not an X.509 certificate: " + e);
            // ignore
        }

        if (cert == null) {
            // TODO: Remove this code. Importing PKCS #7 is not supported.

            // cert chain direction
            boolean assending = true;

            // could it be a pkcs7 blob?
            CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_IS_PK_BLOB"));

            try {
                CryptoManager manager = CryptoManager.getInstance();

                PKCS7 pkcs7 = new PKCS7(binaryCert);

                X509Certificate p7certs[] = pkcs7.getCertificates();

                if (p7certs.length == 0) {
                    CMS.debug("UserService: PKCS #7 data contains no certificates");
                    throw new BadRequestException("PKCS #7 data contains no certificates");
                }

                // fix for 370099 - cert ordering can not be assumed
                // find out the ordering ...

                // self-signed and alone? take it. otherwise test
                // the ordering
                if (p7certs[0].getSubjectDN().toString().equals(p7certs[0].getIssuerDN().toString())
                        && (p7certs.length == 1)) {
                    cert = p7certs[0];
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_SINGLE_CERT_IMPORT"));

                } else if (p7certs[0].getIssuerDN().toString().equals(p7certs[1].getSubjectDN().toString())) {
                    cert = p7certs[0];
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_CHAIN_ACEND_ORD"));

                } else if (p7certs[1].getIssuerDN().toString().equals(p7certs[0].getSubjectDN().toString())) {
                    assending = false;
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_CHAIN_DESC_ORD"));
                    cert = p7certs[p7certs.length - 1];

                } else {
                    // not a chain, or in random order
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_BAD_CHAIN"));
                    throw new BadRequestException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR", headers));
                }

                CMS.debug("UserService: "
                        + CMS.getLogMessage("ADMIN_SRVLT_CHAIN_STORED_DB", String.valueOf(p7certs.length)));

                int j = 0;
                int jBegin = 0;
                int jEnd = 0;

                if (assending == true) {
                    jBegin = 1;
                    jEnd = p7certs.length;
                } else {
                    jBegin = 0;
                    jEnd = p7certs.length - 1;
                }

                // store the chain into cert db, except for the user cert
                for (j = jBegin; j < jEnd; j++) {
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_IN_CHAIN",
                            String.valueOf(j), String.valueOf(p7certs[j].getSubjectDN())));
                    org.mozilla.jss.crypto.X509Certificate leafCert = manager
                            .importCACertPackage(p7certs[j].getEncoded());

                    if (leafCert == null) {
                        CMS.debug("UserService: missing leaf certificate");
                        log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_LEAF_CERT_NULL"));
                    } else {
                        CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_LEAF_CERT_NON_NULL"));
                    }

                    if (leafCert instanceof InternalCertificate) {
                        ((InternalCertificate) leafCert).setSSLTrust(InternalCertificate.VALID_CA
                                | InternalCertificate.TRUSTED_CA | InternalCertificate.TRUSTED_CLIENT_CA);
                    } else {
                        log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NOT_INTERNAL_CERT",
                                String.valueOf(p7certs[j].getSubjectDN())));
                    }
                }

                /*
                } catch (CryptoManager.UserCertConflictException e) {
                // got a "user cert" in the chain, most likely the CA
                // cert of this instance, which has a private key.  Ignore
                log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_PKS7_IGNORED", e.toString()));
                */
            } catch (PKIException e) {
                CMS.debug("UserService: Unable to import user certificate from PKCS #7 data: " + e);
                log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString()));
                throw e;

            } catch (Exception e) {
                CMS.debug(e);
                log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString()));
                throw new PKIException("Unable to import user certificate from PKCS #7 data: " + e.getMessage(),
                        e);
            }
        }

        try {
            CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_BEFORE_VALIDITY"));
            cert.checkValidity(); // throw exception if fails

            user.setX509Certificates(new X509Certificate[] { cert });
            userGroupManager.addUserCert(user);

            auditAddUserCert(userID, userCertData, ILogger.SUCCESS);

            // read the data back

            userCertData.setVersion(cert.getVersion());
            userCertData.setSerialNumber(new CertId(cert.getSerialNumber()));
            userCertData.setIssuerDN(cert.getIssuerDN().toString());
            userCertData.setSubjectDN(cert.getSubjectDN().toString());
            String certID = userCertData.getID();

            userCertData = getUserCertData(userID, URLEncoder.encode(certID, "UTF-8"));

            return createCreatedResponse(userCertData, userCertData.getLink().getHref());

        } catch (CertificateExpiredException e) {
            CMS.debug("UserService: Certificate expired: " + e);
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("ADMIN_SRVLT_ADD_CERT_EXPIRED", String.valueOf(cert.getSubjectDN())));
            throw new BadRequestException("Certificate expired: " + e.getMessage(), e);

        } catch (CertificateNotYetValidException e) {
            CMS.debug("UserService: Certificate not yet valid: " + e);
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("USRGRP_SRVLT_CERT_NOT_YET_VALID", String.valueOf(cert.getSubjectDN())));
            throw new BadRequestException("Certificate not yet valid: " + e.getMessage(), e);
        }

    } catch (PKIException e) {
        CMS.debug("UserService: Unable to import user certificate: " + e);
        auditAddUserCert(userID, userCertData, ILogger.FAILURE);
        throw e;

    } catch (Exception e) {
        CMS.debug(e);
        log(ILogger.LL_FAILURE, e.toString());
        auditAddUserCert(userID, userCertData, ILogger.FAILURE);
        throw new PKIException("Unable to import user certificate: " + e.getMessage(), e);
    }
}