Search in sources :

Example 81 with CertPath

use of java.security.cert.CertPath in project zm-mailbox by Zimbra.

the class CertValidationUtil method validateCertificate.

public static void validateCertificate(X509Certificate cert, boolean revocationCheckEnabled, Set<TrustAnchor> trustedCertsSet) throws CertificateException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, CertPathValidatorException {
    cert.checkValidity();
    if (revocationCheckEnabled) {
        List<X509Certificate> certificates = new ArrayList<X509Certificate>();
        certificates.add(cert);
        CertificateFactory cf;
        CertPath cp;
        cf = CertificateFactory.getInstance("X509");
        cp = cf.generateCertPath(certificates);
        // init PKIX parameters
        PKIXParameters params;
        params = new PKIXParameters(trustedCertsSet);
        params.setRevocationEnabled(revocationCheckEnabled);
        // perform validation
        CertPathValidator cpv;
        cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpv_result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        ZimbraLog.account.debug("Certificate Validation Result %s", cpv_result.toString());
    }
}
Also used : CertPathValidator(java.security.cert.CertPathValidator) PKIXParameters(java.security.cert.PKIXParameters) PKIXCertPathValidatorResult(java.security.cert.PKIXCertPathValidatorResult) ArrayList(java.util.ArrayList) CertPath(java.security.cert.CertPath) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 82 with CertPath

use of java.security.cert.CertPath in project hono by eclipse.

the class DeviceRegistryBasedCertificateVerifier method validateCertificateAndLoadDevice.

/**
 * Validates a device's client certificate and completes the DTLS handshake result handler.
 *
 * @param cid the connection id to report the result.
 * @param certPath certificate path.
 * @param session session.
 * @see #setResultHandler(HandshakeResultHandler)
 */
private void validateCertificateAndLoadDevice(final ConnectionId cid, final CertPath certPath, final DTLSSession session) {
    LOG.debug("validating client's X.509 certificate");
    final Span span = tracer.buildSpan("validate client certificate").withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).withTag(Tags.COMPONENT.getKey(), adapter.getTypeName()).start();
    validateCertificateAndLoadDevice(session, certPath, span).map(info -> {
        // set AdditionalInfo as customArgument here
        return new CertificateVerificationResult(cid, certPath, info);
    }).otherwise(t -> {
        TracingHelper.logError(span, "could not validate X509 for device", t);
        LOG.debug("error validating X509", t);
        final AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer());
        return new CertificateVerificationResult(cid, new HandshakeException("error validating X509", alert), null);
    }).onSuccess(result -> {
        span.finish();
        californiumResultHandler.apply(result);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) X500Principal(javax.security.auth.x500.X500Principal) LoggerFactory(org.slf4j.LoggerFactory) CertificateType(org.eclipse.californium.scandium.dtls.CertificateType) ClientErrorException(org.eclipse.hono.client.ClientErrorException) AlertDescription(org.eclipse.californium.scandium.dtls.AlertMessage.AlertDescription) Tags(io.opentracing.tag.Tags) CertificateMessage(org.eclipse.californium.scandium.dtls.CertificateMessage) ServerName(org.eclipse.californium.scandium.util.ServerName) DeviceCredentials(org.eclipse.hono.adapter.auth.device.DeviceCredentials) HandshakeException(org.eclipse.californium.scandium.dtls.HandshakeException) CertPathUtil(org.eclipse.californium.elements.util.CertPathUtil) ServerNames(org.eclipse.californium.scandium.util.ServerNames) StreamSupport(java.util.stream.StreamSupport) NewAdvancedCertificateVerifier(org.eclipse.californium.scandium.dtls.x509.NewAdvancedCertificateVerifier) TracingHelper(org.eclipse.hono.tracing.TracingHelper) X509Authentication(org.eclipse.hono.adapter.auth.device.X509Authentication) Logger(org.slf4j.Logger) NameType(org.eclipse.californium.scandium.util.ServerName.NameType) Tracer(io.opentracing.Tracer) TenantServiceBasedX509Authentication(org.eclipse.hono.adapter.auth.device.TenantServiceBasedX509Authentication) AlertLevel(org.eclipse.californium.scandium.dtls.AlertMessage.AlertLevel) AdditionalInfo(org.eclipse.californium.elements.auth.AdditionalInfo) Promise(io.vertx.core.Promise) HandshakeResultHandler(org.eclipse.californium.scandium.dtls.HandshakeResultHandler) CertPath(java.security.cert.CertPath) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Objects(java.util.Objects) DTLSSession(org.eclipse.californium.scandium.dtls.DTLSSession) List(java.util.List) Certificate(java.security.cert.Certificate) TenantTraceSamplingHelper(org.eclipse.hono.tracing.TenantTraceSamplingHelper) DeviceCredentialsAuthProvider(org.eclipse.hono.adapter.auth.device.DeviceCredentialsAuthProvider) X509AuthProvider(org.eclipse.hono.adapter.auth.device.X509AuthProvider) ConnectionId(org.eclipse.californium.scandium.dtls.ConnectionId) CertificateVerificationResult(org.eclipse.californium.scandium.dtls.CertificateVerificationResult) Optional(java.util.Optional) AlertMessage(org.eclipse.californium.scandium.dtls.AlertMessage) Span(io.opentracing.Span) SubjectDnCredentials(org.eclipse.hono.adapter.auth.device.SubjectDnCredentials) Span(io.opentracing.Span) HandshakeException(org.eclipse.californium.scandium.dtls.HandshakeException) AlertMessage(org.eclipse.californium.scandium.dtls.AlertMessage) CertificateVerificationResult(org.eclipse.californium.scandium.dtls.CertificateVerificationResult)

Example 83 with CertPath

use of java.security.cert.CertPath in project hono by eclipse.

the class DeviceCertificateValidator method validate.

/**
 * {@inheritDoc}
 */
@Override
public Future<Void> validate(final List<X509Certificate> chain, final Set<TrustAnchor> trustAnchors) {
    Objects.requireNonNull(chain);
    Objects.requireNonNull(trustAnchors);
    if (chain.isEmpty()) {
        throw new IllegalArgumentException("certificate chain must not be empty");
    } else if (trustAnchors.isEmpty()) {
        throw new IllegalArgumentException("trust anchor list must not be empty");
    }
    final Promise<Void> result = Promise.promise();
    try {
        final PKIXParameters params = new PKIXParameters(trustAnchors);
        // TODO do we need to check for revocation?
        params.setRevocationEnabled(false);
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        final CertPath path = factory.generateCertPath(chain);
        final CertPathValidator validator = CertPathValidator.getInstance("PKIX");
        validator.validate(path, params);
        LOG.debug("validation of device certificate [subject DN: {}] succeeded", chain.get(0).getSubjectX500Principal().getName());
        result.complete();
    } catch (GeneralSecurityException e) {
        LOG.debug("validation of device certificate [subject DN: {}] failed", chain.get(0).getSubjectX500Principal().getName(), e);
        if (e instanceof CertificateException) {
            result.fail(e);
        } else {
            result.fail(new CertificateException("validation of device certificate failed", e));
        }
    }
    return result.future();
}
Also used : CertPathValidator(java.security.cert.CertPathValidator) PKIXParameters(java.security.cert.PKIXParameters) GeneralSecurityException(java.security.GeneralSecurityException) CertificateException(java.security.cert.CertificateException) CertPath(java.security.cert.CertPath) CertificateFactory(java.security.cert.CertificateFactory)

Example 84 with CertPath

use of java.security.cert.CertPath in project fabric-sdk-java by hyperledger.

the class CryptoPrimitives method validateCertificate.

boolean validateCertificate(Certificate cert) {
    boolean isValidated;
    if (cert == null) {
        return false;
    }
    try {
        KeyStore keyStore = getTrustStore();
        PKIXParameters parms = new PKIXParameters(keyStore);
        parms.setRevocationEnabled(false);
        // PKIX
        CertPathValidator certValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType());
        ArrayList<Certificate> start = new ArrayList<>();
        start.add(cert);
        CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT);
        CertPath certPath = certFactory.generateCertPath(start);
        certValidator.validate(certPath, parms);
        isValidated = true;
    } catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | CertificateException | CertPathValidatorException | CryptoException e) {
        logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate" + cert.toString());
        isValidated = false;
    }
    return isValidated;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) CertPathValidator(java.security.cert.CertPathValidator) CertPathValidatorException(java.security.cert.CertPathValidatorException) PKIXParameters(java.security.cert.PKIXParameters) CertPath(java.security.cert.CertPath) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 85 with CertPath

use of java.security.cert.CertPath in project open-ecard by ecsec.

the class JavaSecVerifier method isValid.

@Override
public void isValid(TlsServerCertificate chain, String hostname) throws CertificateVerificationException {
    try {
        CertPath certPath = convertChain(chain);
        // create the parameters for the validator
        PKIXParameters params = new PKIXParameters(getTrustStore());
        if (checkRevocation) {
            params.setRevocationEnabled(true);
            System.setProperty("com.sun.security.enableCRLDP", "true");
        } else {
            // disable CRL checking since we are not supplying any CRLs yet
            params.setRevocationEnabled(false);
        }
        // validate - exception marks failure
        certPathValidator.validate(certPath, params);
    } catch (CertPathValidatorException ex) {
        throw new CertificateVerificationException(ex.getMessage());
    } catch (GeneralSecurityException ex) {
        throw new CertificateVerificationException(ex.getMessage());
    } catch (IOException ex) {
        throw new CertificateVerificationException("Error converting certificate chain to java.security format.");
    }
}
Also used : CertPathValidatorException(java.security.cert.CertPathValidatorException) CertificateVerificationException(org.openecard.crypto.tls.CertificateVerificationException) PKIXParameters(java.security.cert.PKIXParameters) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) CertPath(java.security.cert.CertPath)

Aggregations

CertPath (java.security.cert.CertPath)86 X509Certificate (java.security.cert.X509Certificate)36 CertificateFactory (java.security.cert.CertificateFactory)29 Certificate (java.security.cert.Certificate)19 CertPathValidator (java.security.cert.CertPathValidator)18 CertPathValidatorException (java.security.cert.CertPathValidatorException)18 MyCertPath (org.apache.harmony.security.tests.support.cert.MyCertPath)17 CertificateException (java.security.cert.CertificateException)15 ArrayList (java.util.ArrayList)15 PKIXParameters (java.security.cert.PKIXParameters)14 MyFailingCertPath (org.apache.harmony.security.tests.support.cert.MyFailingCertPath)14 TrustAnchor (java.security.cert.TrustAnchor)12 HashSet (java.util.HashSet)12 ByteArrayInputStream (java.io.ByteArrayInputStream)11 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)11 CertPathBuilderResult (java.security.cert.CertPathBuilderResult)11 PKIXBuilderParameters (java.security.cert.PKIXBuilderParameters)10 PKIXCertPathValidatorResult (java.security.cert.PKIXCertPathValidatorResult)10 X509CertSelector (java.security.cert.X509CertSelector)10 CertPathBuilder (java.security.cert.CertPathBuilder)9