Search in sources :

Example 6 with CertificateNotYetValidException

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

the class JettySSLService method logAndValidateCertificate.

private void logAndValidateCertificate() throws ServiceLifecycleException {
    // let's log the hostname (CN) and cert expiry from the gateway's public cert to aid in SSL debugging
    Certificate cert;
    try {
        cert = as.getCertificateForGateway("gateway-identity");
    } catch (AliasServiceException e) {
        throw new ServiceLifecycleException("Cannot Retreive Gateway SSL Certificate. Server will not start.", e);
    }
    if (cert != null) {
        if (cert instanceof X509Certificate) {
            X500Principal x500Principal = ((X509Certificate) cert).getSubjectX500Principal();
            X500PrincipalParser parser = new X500PrincipalParser(x500Principal);
            log.certificateHostNameForGateway(parser.getCN());
            Date notBefore = ((X509Certificate) cert).getNotBefore();
            Date notAfter = ((X509Certificate) cert).getNotAfter();
            log.certificateValidityPeriod(notBefore, notAfter);
            // let's not even start if the current date is not within the validity period for the SSL cert
            try {
                ((X509Certificate) cert).checkValidity();
            } catch (CertificateExpiredException e) {
                throw new ServiceLifecycleException("Gateway SSL Certificate is Expired. Server will not start.", e);
            } catch (CertificateNotYetValidException e) {
                throw new ServiceLifecycleException("Gateway SSL Certificate is not yet valid. Server will not start.", e);
            }
        } else {
            throw new ServiceLifecycleException("Public certificate for the gateway cannot be found with the alias gateway-identity. Plase check the identity certificate alias.");
        }
    } else {
        throw new ServiceLifecycleException("Public certificate for the gateway is not of the expected type of X509Certificate. Something is wrong with the gateway keystore.");
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) X500PrincipalParser(org.apache.knox.gateway.util.X500PrincipalParser) CertificateExpiredException(java.security.cert.CertificateExpiredException) AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) ServiceLifecycleException(org.apache.knox.gateway.services.ServiceLifecycleException) X500Principal(javax.security.auth.x500.X500Principal) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 7 with CertificateNotYetValidException

use of java.security.cert.CertificateNotYetValidException in project santuario-java by apache.

the class CertsInFilesystemDirectoryResolver method readCertsFromHarddrive.

/**
 * Method readCertsFromHarddrive
 *
 * @throws StorageResolverException
 */
private void readCertsFromHarddrive() throws StorageResolverException {
    File certDir = new File(this.merlinsCertificatesDir);
    List<String> al = new ArrayList<>();
    String[] names = certDir.list();
    if (names != null) {
        for (int i = 0; i < names.length; i++) {
            String currentFileName = names[i];
            if (currentFileName.endsWith(".crt")) {
                al.add(names[i]);
            }
        }
    }
    CertificateFactory cf = null;
    try {
        cf = CertificateFactory.getInstance("X.509");
    } catch (CertificateException ex) {
        throw new StorageResolverException(ex);
    }
    for (int i = 0; i < al.size(); i++) {
        String filename = certDir.getAbsolutePath() + File.separator + al.get(i);
        boolean added = false;
        String dn = null;
        try (InputStream inputStream = Files.newInputStream(Paths.get(filename))) {
            X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
            // add to ArrayList
            cert.checkValidity();
            this.certs.add(cert);
            dn = cert.getSubjectX500Principal().getName();
            added = true;
        } catch (FileNotFoundException ex) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (CertificateNotYetValidException ex) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (CertificateExpiredException ex) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (CertificateException ex) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (IOException ex) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Could not add certificate from file " + filename, ex);
            }
        }
        if (added) {
            LOG.debug("Added certificate: {}", dn);
        }
    }
}
Also used : StorageResolverException(org.apache.xml.security.keys.storage.StorageResolverException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) File(java.io.File)

Example 8 with CertificateNotYetValidException

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

the class KeyStoreUtil method addCert.

/**
 *  Load an X509 Cert from a file and add it to the
 *  trusted set of certificates in the key store
 *
 *  This DOES check for revocation, IF cs is non-null.
 *
 *  @param cs may be null; if non-null, check for revocation
 *  @return success
 *  @since 0.9.25
 */
public static boolean addCert(File file, String alias, KeyStore ks, CertStore cs) {
    try {
        X509Certificate cert = CertUtil.loadCert(file);
        info("Read X509 Certificate from " + file.getAbsolutePath() + " Issuer: " + cert.getIssuerX500Principal() + " Serial: " + cert.getSerialNumber().toString(16) + "; Valid From: " + cert.getNotBefore() + " To: " + cert.getNotAfter());
        if (cs != null && CertUtil.isRevoked(cs, cert)) {
            error("Certificate is revoked: " + file, new Exception());
            return false;
        }
        ks.setCertificateEntry(alias, cert);
        info("Now trusting X509 Certificate, Issuer: " + cert.getIssuerX500Principal());
    } catch (CertificateExpiredException cee) {
        String s = "Rejecting expired X509 Certificate: " + file.getAbsolutePath();
        // Android often has old system certs
        // our SSL certs may be old also
        // if (SystemVersion.isAndroid())
        warn(s, cee);
        // error(s, cee);
        return false;
    } catch (CertificateNotYetValidException cnyve) {
        error("Rejecting X509 Certificate not yet valid: " + file.getAbsolutePath(), cnyve);
        return false;
    } catch (GeneralSecurityException gse) {
        error("Error reading X509 Certificate: " + file.getAbsolutePath(), gse);
        return false;
    } catch (IOException ioe) {
        error("Error reading X509 Certificate: " + file.getAbsolutePath(), ioe);
        return false;
    }
    return true;
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) KeyStoreException(java.security.KeyStoreException) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException)

Example 9 with CertificateNotYetValidException

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

the class KeyStoreUtil method logCertExpiration.

/**
 *  Validate expiration for all private key certs in a key store.
 *  Use this for keystores containing selfsigned certs where the
 *  user will be expected to renew an expiring cert.
 *  Use this for keystores we are feeding to an SSLContext and ServerSocketFactory.
 *
 *  We added support for self-signed certs in 0.8.3 2011-01, with a 10-year expiration.
 *  We still don't generate them by default. We don't expect anybody's
 *  certs to expire until 2021.
 *
 *  @param location the path or other identifying info, for logging only
 *  @param expiresWithin ms if cert expires within this long, we will log a warning, e.g. 180*24*60*60*1000L
 *  @return true if all are good, false if we logged something
 *  @since 0.9.34
 */
public static boolean logCertExpiration(KeyStore ks, String location, long expiresWithin) {
    boolean rv = true;
    try {
        int count = 0;
        for (Enumeration<String> e = ks.aliases(); e.hasMoreElements(); ) {
            String alias = e.nextElement();
            if (ks.isKeyEntry(alias)) {
                Certificate[] cs;
                try {
                    cs = ks.getCertificateChain(alias);
                } catch (KeyStoreException kse) {
                    error("Unable to check certificates for \"" + alias + "\" in key store " + location, kse);
                    rv = false;
                    continue;
                }
                for (Certificate c : cs) {
                    if (c != null && (c instanceof X509Certificate)) {
                        count++;
                        X509Certificate cert = (X509Certificate) c;
                        try {
                            // System.out.println("checking " + alias + " in " + location);
                            cert.checkValidity();
                            long expiresIn = cert.getNotAfter().getTime() - System.currentTimeMillis();
                            // System.out.println("expiration of " + alias + " is in " + DataHelper.formatDuration(expiresIn));
                            if (expiresIn < expiresWithin) {
                                Log l = I2PAppContext.getGlobalContext().logManager().getLog(KeyStoreUtil.class);
                                String subj = cert.getIssuerX500Principal().toString();
                                l.logAlways(Log.WARN, "Certificate \"" + subj + "\" in key store " + location + " will expire in " + DataHelper.formatDuration2(expiresIn).replace("&nbsp;", " ") + "\nYou should renew the certificate soon." + // TODO better help or tools, or autorenew
                                "\nFor a local self-signed certificate, you may delete the keystore and restart," + " or ask for help on how to renew.");
                            }
                        } catch (CertificateExpiredException cee) {
                            String subj = cert.getIssuerX500Principal().toString();
                            error("Expired certificate \"" + subj + "\" in key store " + location + "\nYou must renew the certificate." + // TODO better help or tools, or autorenew
                            "\nFor a local self-signed certificate, you may simply delete the keystore and restart," + "\nor ask for help on how to renew.", null);
                            rv = false;
                        } catch (CertificateNotYetValidException cnyve) {
                            String subj = cert.getIssuerX500Principal().toString();
                            error("Not yet valid certificate \"" + subj + "\" in key store " + location, null);
                            rv = false;
                        }
                    }
                }
            }
        }
        if (count == 0)
            error("No certificates found in key store " + location, null);
    } catch (GeneralSecurityException e) {
        error("Unable to check certificates in key store " + location, e);
        rv = false;
    }
    return rv;
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) Log(net.i2p.util.Log) GeneralSecurityException(java.security.GeneralSecurityException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 10 with CertificateNotYetValidException

use of java.security.cert.CertificateNotYetValidException in project nifi-registry by apache.

the class X509IdentityProvider method authenticate.

/**
 * For a given {@link AuthenticationRequest}, this validates the client certificate and creates a populated {@link AuthenticationResponse}.
 *
 * The {@link AuthenticationRequest} authenticationRequest paramenter is expected to be populated as:
 *  - username: principal DN from first client cert
 *  - credentials: first client certificate (X509Certificate)
 *  - details: proxied-entities chain (String)
 *
 * @param authenticationRequest the request, containing identity claim credentials for the IdentityProvider to authenticate and determine an identity
 */
@Override
public AuthenticationResponse authenticate(AuthenticationRequest authenticationRequest) throws InvalidCredentialsException {
    if (authenticationRequest == null || authenticationRequest.getUsername() == null) {
        return null;
    }
    String principal = authenticationRequest.getUsername();
    try {
        X509Certificate clientCertificate = (X509Certificate) authenticationRequest.getCredentials();
        validateClientCertificate(clientCertificate);
    } catch (CertificateExpiredException cee) {
        final String message = String.format("Client certificate for (%s) is expired.", principal);
        logger.warn(message, cee);
        throw new InvalidCredentialsException(message, cee);
    } catch (CertificateNotYetValidException cnyve) {
        final String message = String.format("Client certificate for (%s) is not yet valid.", principal);
        logger.warn(message, cnyve);
        throw new InvalidCredentialsException(message, cnyve);
    } catch (final Exception e) {
        logger.warn(e.getMessage(), e);
    }
    // build the authentication response
    return new AuthenticationResponse(principal, principal, expiration, issuer);
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) InvalidCredentialsException(org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException) AuthenticationResponse(org.apache.nifi.registry.security.authentication.AuthenticationResponse) X509Certificate(java.security.cert.X509Certificate) SecurityProviderCreationException(org.apache.nifi.registry.security.exception.SecurityProviderCreationException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) SecurityProviderDestructionException(org.apache.nifi.registry.security.exception.SecurityProviderDestructionException) InvalidCredentialsException(org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException)

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