Search in sources :

Example 41 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException 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 42 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException 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)

Example 43 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project j2objc by google.

the class CertificateExpiredExceptionTest method testCertificateExpiredException02.

/**
 * Test for <code>CertificateExpiredException(String)</code> constructor
 * Assertion: constructs CertificateExpiredException with detail message
 * msg. Parameter <code>msg</code> is not null.
 */
public void testCertificateExpiredException02() {
    CertificateExpiredException tE;
    for (int i = 0; i < msgs.length; i++) {
        tE = new CertificateExpiredException(msgs[i]);
        assertEquals("getMessage() must return: ".concat(msgs[i]), tE.getMessage(), msgs[i]);
        assertNull("getCause() must return null", tE.getCause());
    }
}
Also used : CertificateExpiredException(java.security.cert.CertificateExpiredException)

Example 44 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project openremote by openremote.

the class UserAssetProvisioningMQTTHandler method getMatchingX509ProvisioningConfig.

protected X509ProvisioningConfig getMatchingX509ProvisioningConfig(MqttConnection connection, X509Certificate clientCertificate) {
    return provisioningService.getProvisioningConfigs().stream().filter(config -> config instanceof X509ProvisioningConfig).map(config -> (X509ProvisioningConfig) config).filter(config -> {
        try {
            X509Certificate caCertificate = config.getCertificate();
            if (caCertificate != null) {
                if (caCertificate.getSubjectX500Principal().getName().equals(clientCertificate.getIssuerX500Principal().getName())) {
                    LOG.fine("Client certificate issuer matches provisioning config CA certificate subject: connection=" + connection + ", config=" + config);
                    Date now = Date.from(timerService.getNow());
                    try {
                        clientCertificate.verify(caCertificate.getPublicKey());
                        LOG.fine("Client certificate verified against CA certificate: connection=" + connection + ", config=" + config);
                        if (!config.getData().isIgnoreExpiryDate()) {
                            LOG.fine("Validating client certificate validity: connection=" + connection + ", timestamp=" + now);
                            clientCertificate.checkValidity(now);
                        }
                        return true;
                    } catch (CertificateExpiredException | CertificateNotYetValidException e) {
                        LOG.log(Level.INFO, "Client certificate failed validity check: connection=" + connection + ", timestamp=" + now, e);
                    } catch (Exception e) {
                        LOG.log(Level.INFO, "Client certificate failed verification against CA certificate: connection=" + connection + ", config=" + config, e);
                    }
                }
            }
        } catch (Exception e) {
            LOG.log(Level.WARNING, "Failed to extract certificate from provisioning config: config=" + config, e);
        }
        return false;
    }).findFirst().orElse(null);
}
Also used : AssetStorageService(org.openremote.manager.asset.AssetStorageService) X509Certificate(java.security.cert.X509Certificate) Topic(io.moquette.broker.subscriptions.Topic) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) ManagerKeycloakIdentityProvider(org.openremote.manager.security.ManagerKeycloakIdentityProvider) UserAssetLink(org.openremote.model.asset.UserAssetLink) java.util(java.util) ClientRole(org.openremote.model.security.ClientRole) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) InterceptPublishMessage(io.moquette.interception.messages.InterceptPublishMessage) MQTTHandler(org.openremote.manager.mqtt.MQTTHandler) ValueUtil(org.openremote.model.util.ValueUtil) RESTRICTED_USER_REALM_ROLE(org.openremote.model.Constants.RESTRICTED_USER_REALM_ROLE) CertificateExpiredException(java.security.cert.CertificateExpiredException) Level(java.util.logging.Level) UniqueIdentifierGenerator(org.openremote.container.util.UniqueIdentifierGenerator) InterceptConnectionLostMessage(io.moquette.interception.messages.InterceptConnectionLostMessage) SyslogCategory(org.openremote.model.syslog.SyslogCategory) TextUtil(org.openremote.model.util.TextUtil) PersistenceEvent(org.openremote.model.PersistenceEvent) MessageBrokerService(org.openremote.container.message.MessageBrokerService) User(org.openremote.model.security.User) InterceptUnsubscribeMessage(io.moquette.interception.messages.InterceptUnsubscribeMessage) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) InterceptSubscribeMessage(io.moquette.interception.messages.InterceptSubscribeMessage) Asset(org.openremote.model.asset.Asset) API(org.openremote.model.syslog.SyslogCategory.API) org.openremote.model.provisioning(org.openremote.model.provisioning) MqttConnection(org.openremote.manager.mqtt.MqttConnection) CertificateException(java.security.cert.CertificateException) Logger(java.util.logging.Logger) StandardCharsets(java.nio.charset.StandardCharsets) Container(org.openremote.model.Container) MqttBrokerService(org.openremote.manager.mqtt.MqttBrokerService) RouteBuilder(org.apache.camel.builder.RouteBuilder) TimerService(org.openremote.container.timer.TimerService) PERSISTENCE_TOPIC(org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC) PersistenceService.isPersistenceEventForEntityType(org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) X509Certificate(java.security.cert.X509Certificate) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) CertificateException(java.security.cert.CertificateException)

Example 45 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project qpid-broker-j by apache.

the class FileTrustStoreTest method testUseOfExpiredTrustAnchorDenied.

@Test
public void testUseOfExpiredTrustAnchorDenied() throws Exception {
    final Path keyStoreFile = createTrustStoreWithExpiredCertificate();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(FileTrustStore.NAME, NAME);
    attributes.put(FileTrustStore.TRUST_ANCHOR_VALIDITY_ENFORCED, true);
    attributes.put(FileTrustStore.STORE_URL, keyStoreFile.toFile().getAbsolutePath());
    attributes.put(FileTrustStore.PASSWORD, TLS_RESOURCE.getSecret());
    attributes.put(FileTrustStore.TRUST_STORE_TYPE, TLS_RESOURCE.getKeyStoreType());
    final TrustStore<?> trustStore = createFileTrustStore(attributes);
    TrustManager[] trustManagers = trustStore.getTrustManagers();
    assertNotNull(trustManagers);
    assertEquals("Unexpected number of trust managers", 1, trustManagers.length);
    final boolean condition = trustManagers[0] instanceof X509TrustManager;
    assertTrue("Unexpected trust manager type", condition);
    X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
    KeyStore clientStore = getInitializedKeyStore(keyStoreFile.toFile().getAbsolutePath(), TLS_RESOURCE.getSecret(), TLS_RESOURCE.getKeyStoreType());
    String alias = clientStore.aliases().nextElement();
    X509Certificate certificate = (X509Certificate) clientStore.getCertificate(alias);
    try {
        trustManager.checkClientTrusted(new X509Certificate[] { certificate }, "NULL");
        fail("Exception not thrown");
    } catch (CertificateException e) {
        if (e instanceof CertificateExpiredException || "Certificate expired".equals(e.getMessage())) {
        // IBMJSSE2 does not throw CertificateExpiredException, it throws a CertificateException
        // ignore
        } else {
            throw e;
        }
    }
}
Also used : Path(java.nio.file.Path) CertificateExpiredException(java.security.cert.CertificateExpiredException) HashMap(java.util.HashMap) CertificateException(java.security.cert.CertificateException) SSLUtil.getInitializedKeyStore(org.apache.qpid.server.transport.network.security.ssl.SSLUtil.getInitializedKeyStore) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) TrustManager(javax.net.ssl.TrustManager) QpidPeersOnlyTrustManager(org.apache.qpid.server.transport.network.security.ssl.QpidPeersOnlyTrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) Test(org.junit.Test)

Aggregations

CertificateExpiredException (java.security.cert.CertificateExpiredException)46 X509Certificate (java.security.cert.X509Certificate)32 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)28 CertificateException (java.security.cert.CertificateException)15 ArrayList (java.util.ArrayList)7 GeneralSecurityException (java.security.GeneralSecurityException)6 InvalidKeyException (java.security.InvalidKeyException)6 KeyStore (java.security.KeyStore)6 Certificate (java.security.cert.Certificate)6 IOException (java.io.IOException)5 KeyStoreException (java.security.KeyStoreException)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 Date (java.util.Date)5 SuppressLint (android.annotation.SuppressLint)4 Principal (java.security.Principal)4 Calendar (java.util.Calendar)4 Test (org.junit.Test)4 FileNotFoundException (java.io.FileNotFoundException)3 CertificateFactory (java.security.cert.CertificateFactory)3 X509TrustManager (javax.net.ssl.X509TrustManager)3