Search in sources :

Example 26 with CertificateNotYetValidException

use of java.security.cert.CertificateNotYetValidException in project coprhd-controller by CoprHD.

the class SSLUtil method certificateIsTrusted.

/**
 * certificateIsTrusted
 *
 * @param certToCheck
 */
public boolean certificateIsTrusted(Certificate certToCheck) throws InvalidCertificate {
    try {
        KeyStore ts = KeyStore.getInstance("JKS");
        FileInputStream is = new FileInputStream(trustStoreFileName);
        ts.load(is, trustStorePassword.toCharArray());
        is.close();
        Enumeration<String> aliases = ts.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (ts.isCertificateEntry(alias)) {
                /**
                 * certificate is trusted
                 */
                X509Certificate tc = (X509Certificate) ts.getCertificate(alias);
                try {
                    tc.checkValidity();
                    /**
                     * certificate is valid
                     */
                    if (tc.equals(certToCheck)) {
                        return true;
                    } else {
                        log.warn("Certificate [" + alias + "] is not valid.");
                    }
                } catch (CertificateNotYetValidException e) {
                    log.error("Certificate is not yet valid: ", e);
                    throw e;
                } catch (CertificateExpiredException e) {
                    log.error("Certificate is expired: ", e);
                    throw e;
                }
            /*
                       * catch (InvalidCertificate e) {
                       * throw e;
                       * }
                       */
            }
        }
        return false;
    } catch (Exception e) {
        throw FaultUtil.InvalidCertificate("Exception: " + e);
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 27 with CertificateNotYetValidException

use of java.security.cert.CertificateNotYetValidException in project netty by netty.

the class SslErrorTest method data.

static Collection<Object[]> data() {
    List<SslProvider> serverProviders = new ArrayList<SslProvider>(2);
    List<SslProvider> clientProviders = new ArrayList<SslProvider>(3);
    if (OpenSsl.isAvailable()) {
        serverProviders.add(SslProvider.OPENSSL);
        serverProviders.add(SslProvider.OPENSSL_REFCNT);
        clientProviders.add(SslProvider.OPENSSL);
        clientProviders.add(SslProvider.OPENSSL_REFCNT);
    }
    // We not test with SslProvider.JDK on the server side as the JDK implementation currently just send the same
    // alert all the time, sigh.....
    clientProviders.add(SslProvider.JDK);
    List<CertificateException> exceptions = new ArrayList<CertificateException>(6);
    exceptions.add(new CertificateExpiredException());
    exceptions.add(new CertificateNotYetValidException());
    exceptions.add(new CertificateRevokedException(new Date(), CRLReason.AA_COMPROMISE, new X500Principal(""), Collections.<String, Extension>emptyMap()));
    // Also use wrapped exceptions as this is what the JDK implementation of X509TrustManagerFactory is doing.
    exceptions.add(newCertificateException(CertPathValidatorException.BasicReason.EXPIRED));
    exceptions.add(newCertificateException(CertPathValidatorException.BasicReason.NOT_YET_VALID));
    exceptions.add(newCertificateException(CertPathValidatorException.BasicReason.REVOKED));
    List<Object[]> params = new ArrayList<Object[]>();
    for (SslProvider serverProvider : serverProviders) {
        for (SslProvider clientProvider : clientProviders) {
            for (CertificateException exception : exceptions) {
                params.add(new Object[] { serverProvider, clientProvider, exception, true });
                params.add(new Object[] { serverProvider, clientProvider, exception, false });
            }
        }
    }
    return params;
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) CertificateRevokedException(java.security.cert.CertificateRevokedException) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) Date(java.util.Date) Extension(java.security.cert.Extension) X500Principal(javax.security.auth.x500.X500Principal)

Example 28 with CertificateNotYetValidException

use of java.security.cert.CertificateNotYetValidException in project oxAuth by GluuFederation.

the class GenericCertificateVerifier method validate.

@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) {
    X509Certificate issuer = issuers.get(0);
    ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.APP, CertificateValidity.UNKNOWN);
    try {
        Principal subjectX500Principal = certificate.getSubjectX500Principal();
        try {
            log.debug("Validity status is valid for '" + subjectX500Principal + "'");
            certificate.checkValidity(validationDate);
            status.setValidity(CertificateValidity.VALID);
        } catch (CertificateExpiredException ex) {
            log.debug("Validity status is expied for '" + subjectX500Principal + "'");
        } catch (CertificateNotYetValidException ex) {
            log.warn("Validity status is not yet valid for '" + subjectX500Principal + "'");
        }
    } catch (Exception ex) {
        log.error("CRL exception: ", ex);
    }
    return status;
}
Also used : ValidationStatus(org.gluu.oxauth.cert.validation.model.ValidationStatus) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) X509Certificate(java.security.cert.X509Certificate) Principal(java.security.Principal) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException)

Example 29 with CertificateNotYetValidException

use of java.security.cert.CertificateNotYetValidException in project cloudstack by apache.

the class RootCACustomTrustManager method checkClientTrusted.

@Override
public void checkClientTrusted(final X509Certificate[] certificates, final String s) throws CertificateException {
    if (LOG.isDebugEnabled()) {
        printCertificateChain(certificates, s);
    }
    final X509Certificate primaryClientCertificate = (certificates != null && certificates.length > 0 && certificates[0] != null) ? certificates[0] : null;
    String exceptionMsg = "";
    if (authStrictness && primaryClientCertificate == null) {
        throw new CertificateException("In strict auth mode, certificate(s) are expected from client:" + clientAddress);
    } else if (primaryClientCertificate == null) {
        LOG.info("No certificate was received from client, but continuing since strict auth mode is disabled");
        return;
    }
    // Revocation check
    final BigInteger serialNumber = primaryClientCertificate.getSerialNumber();
    if (serialNumber == null || crlDao.findBySerial(serialNumber) != null) {
        final String errorMsg = String.format("Client is using revoked certificate of serial=%x, subject=%s from address=%s", primaryClientCertificate.getSerialNumber(), primaryClientCertificate.getSubjectDN(), clientAddress);
        LOG.error(errorMsg);
        exceptionMsg = (StringUtils.isEmpty(exceptionMsg)) ? errorMsg : (exceptionMsg + ". " + errorMsg);
    }
    // Validity check
    try {
        primaryClientCertificate.checkValidity();
    } catch (final CertificateExpiredException | CertificateNotYetValidException e) {
        final String errorMsg = String.format("Client certificate has expired with serial=%x, subject=%s from address=%s", primaryClientCertificate.getSerialNumber(), primaryClientCertificate.getSubjectDN(), clientAddress);
        LOG.error(errorMsg);
        if (!allowExpiredCertificate) {
            throw new CertificateException(errorMsg);
        }
    }
    // Ownership check
    boolean certMatchesOwnership = false;
    if (primaryClientCertificate.getSubjectAlternativeNames() != null) {
        for (final List<?> list : primaryClientCertificate.getSubjectAlternativeNames()) {
            if (list != null && list.size() == 2 && list.get(1) instanceof String) {
                final String alternativeName = (String) list.get(1);
                if (clientAddress.equals(alternativeName)) {
                    certMatchesOwnership = true;
                }
            }
        }
    }
    if (!certMatchesOwnership) {
        final String errorMsg = "Certificate ownership verification failed for client: " + clientAddress;
        LOG.error(errorMsg);
        exceptionMsg = (StringUtils.isEmpty(exceptionMsg)) ? errorMsg : (exceptionMsg + ". " + errorMsg);
    }
    if (authStrictness && StringUtils.isNotEmpty(exceptionMsg)) {
        throw new CertificateException(exceptionMsg);
    }
    if (LOG.isDebugEnabled()) {
        if (authStrictness) {
            LOG.debug("Client/agent connection from ip=" + clientAddress + " has been validated and trusted.");
        } else {
            LOG.debug("Client/agent connection from ip=" + clientAddress + " accepted without certificate validation.");
        }
    }
    if (primaryClientCertificate != null && activeCertMap != null && StringUtils.isNotEmpty(clientAddress)) {
        activeCertMap.put(clientAddress, primaryClientCertificate);
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) BigInteger(java.math.BigInteger) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate)

Example 30 with CertificateNotYetValidException

use of java.security.cert.CertificateNotYetValidException in project jmeter by apache.

the class ProxyControl method initDynamicKeyStore.

/**
 * Initialise the dynamic domain keystore
 */
@SuppressWarnings("JdkObsolete")
private void initDynamicKeyStore() throws IOException, GeneralSecurityException {
    if (storePassword != null) {
        // Assume we have already created the store
        try {
            keyStore = getKeyStore(storePassword.toCharArray());
            for (String alias : KeyToolUtils.getCAaliases()) {
                X509Certificate caCert = (X509Certificate) keyStore.getCertificate(alias);
                if (caCert == null) {
                    // no CA key - probably the wrong store type.
                    keyStore = null;
                    // cannot continue
                    break;
                } else {
                    caCert.checkValidity(new Date(System.currentTimeMillis() + DateUtils.MILLIS_PER_DAY));
                    log.info("Valid alias found for {}", alias);
                }
            }
        } catch (IOException e) {
            // store is faulty, we need to recreate it
            // if cert is not valid, flag up to recreate it
            keyStore = null;
            if (e.getCause() instanceof UnrecoverableKeyException) {
                log.warn("Could not read key store {}; cause: {}, a new one will be created, ensure you install it in browser", e.getMessage(), e.getCause().getMessage(), e);
            } else {
                log.warn("Could not open/read key store {}, a new one will be created, ensure you install it in browser", e.getMessage(), // message includes the file name
                e);
            }
        } catch (CertificateExpiredException e) {
            // if cert is not valid, flag up to recreate it
            keyStore = null;
            log.warn("Existing ROOT Certificate has expired, a new one will be created, ensure you install it in browser, message: {}", e.getMessage(), e);
        } catch (CertificateNotYetValidException e) {
            // if cert is not valid, flag up to recreate it
            keyStore = null;
            log.warn("Existing ROOT Certificate is not yet valid, a new one will be created, ensure you install it in browser, message: {}", e.getMessage(), e);
        } catch (GeneralSecurityException e) {
            // if cert is not valid, flag up to recreate it
            keyStore = null;
            log.warn("Problem reading key store, a new one will be created, ensure you install it in browser, message: {}", e.getMessage(), e);
        }
    }
    if (keyStore == null) {
        // no existing file or not valid
        // Alphanum to avoid issues with command-line quoting
        storePassword = JOrphanUtils.generateRandomAlphanumericPassword(20);
        // we use same password for both
        keyPassword = storePassword;
        setPassword(storePassword);
        log.info("Creating HTTP(S) Test Script Recorder Root CA in {}, ensure you install certificate in your Browser for recording", CERT_PATH_ABS);
        KeyToolUtils.generateProxyCA(CERT_PATH, storePassword, CERT_VALIDITY);
        log.info("Created keystore in {}", CERT_PATH_ABS);
        // This should now work
        keyStore = getKeyStore(storePassword.toCharArray());
    }
    final String sslDomains = getSslDomains().trim();
    if (sslDomains.length() > 0) {
        final String[] domains = sslDomains.split(",");
        // The subject may be either a host or a domain
        for (String subject : domains) {
            if (isValid(subject)) {
                if (!keyStore.containsAlias(subject)) {
                    log.info("Creating entry {} in {}", subject, CERT_PATH_ABS);
                    KeyToolUtils.generateHostCert(CERT_PATH, storePassword, subject, CERT_VALIDITY);
                    // reload to pick up new aliases
                    keyStore = getKeyStore(storePassword.toCharArray());
                // reloading is very quick compared with creating an entry currently
                }
            } else {
                log.warn("Attempt to create an invalid domain certificate: {}", subject);
            }
        }
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date)

Aggregations

CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)32 CertificateExpiredException (java.security.cert.CertificateExpiredException)26 X509Certificate (java.security.cert.X509Certificate)25 CertificateException (java.security.cert.CertificateException)10 GeneralSecurityException (java.security.GeneralSecurityException)6 Certificate (java.security.cert.Certificate)6 ArrayList (java.util.ArrayList)6 IOException (java.io.IOException)5 KeyStoreException (java.security.KeyStoreException)5 Date (java.util.Date)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Principal (java.security.Principal)4 File (java.io.File)3 FileNotFoundException (java.io.FileNotFoundException)3 MessageFormat (java.text.MessageFormat)3 List (java.util.List)3 FileInputStream (java.io.FileInputStream)2 BigInteger (java.math.BigInteger)2 SocketTimeoutException (java.net.SocketTimeoutException)2 URISyntaxException (java.net.URISyntaxException)2