Search in sources :

Example 36 with Certificate

use of com.beanit.asn1bean.compiler.pkix1explicit88.Certificate in project jasn1 by openmuc.

the class AuthenticateResponseOk method decode.

public int decode(InputStream is, boolean withTag) throws IOException {
    int tlByteCount = 0;
    int vByteCount = 0;
    BerTag berTag = new BerTag();
    if (withTag) {
        tlByteCount += tag.decodeAndCheck(is);
    }
    BerLength length = new BerLength();
    tlByteCount += length.decode(is);
    int lengthVal = length.val;
    vByteCount += berTag.decode(is);
    if (berTag.equals(EuiccSigned1.tag)) {
        euiccSigned1 = new EuiccSigned1();
        vByteCount += euiccSigned1.decode(is, false);
        vByteCount += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match mandatory sequence component.");
    }
    if (berTag.equals(BerTag.APPLICATION_CLASS, BerTag.PRIMITIVE, 55)) {
        euiccSignature1 = new BerOctetString();
        vByteCount += euiccSignature1.decode(is, false);
        vByteCount += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match mandatory sequence component.");
    }
    if (berTag.equals(Certificate.tag)) {
        euiccCertificate = new Certificate();
        vByteCount += euiccCertificate.decode(is, false);
        vByteCount += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match mandatory sequence component.");
    }
    if (berTag.equals(Certificate.tag)) {
        eumCertificate = new Certificate();
        vByteCount += eumCertificate.decode(is, false);
        if (lengthVal >= 0 && vByteCount == lengthVal) {
            return tlByteCount + vByteCount;
        }
        vByteCount += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match mandatory sequence component.");
    }
    if (lengthVal < 0) {
        while (!berTag.equals(0, 0, 0)) {
            vByteCount += DecodeUtil.decodeUnknownComponent(is);
            vByteCount += berTag.decode(is);
        }
        vByteCount += BerLength.readEocByte(is);
        return tlByteCount + vByteCount;
    } else {
        while (vByteCount < lengthVal) {
            vByteCount += DecodeUtil.decodeUnknownComponent(is);
            if (vByteCount == lengthVal) {
                return tlByteCount + vByteCount;
            }
            vByteCount += berTag.decode(is);
        }
    }
    throw new IOException("Unexpected end of sequence, length tag: " + lengthVal + ", bytes decoded: " + vByteCount);
}
Also used : IOException(java.io.IOException) Certificate(com.beanit.asn1bean.compiler.pkix1explicit88.Certificate)

Example 37 with Certificate

use of com.beanit.asn1bean.compiler.pkix1explicit88.Certificate in project ddf by codice.

the class OcspChecker method getStatusFromOcspResponse.

/**
 * Gets the {@link CertificateStatus} from the given {@param ocspResponse}.
 *
 * @param ocspResponse - the {@link OCSPResp} to get the {@link CertificateStatus} from.
 * @return the {@link CertificateStatus} from the given {@param ocspResponse}. Returns an {@link
 *     UnknownStatus} if the status could not be found.
 */
private CertificateStatus getStatusFromOcspResponse(OCSPResp ocspResponse, X509Certificate certificate) {
    try {
        BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
        if (basicResponse == null) {
            return new UnknownStatus();
        }
        SingleResp[] singleResps = basicResponse.getResponses();
        if (singleResps == null) {
            return new UnknownStatus();
        }
        SingleResp response = Arrays.stream(singleResps).filter(singleResp -> singleResp.getCertID() != null).filter(singleResp -> singleResp.getCertID().getSerialNumber().equals(certificate.getSerialNumber())).findFirst().orElse(null);
        if (response == null) {
            LOGGER.debug("Certificate status from OCSP response is unknown.");
            return new UnknownStatus();
        }
        if (response.getCertStatus() == null) {
            LOGGER.debug("Certificate status from OCSP response is good.");
            return CertificateStatus.GOOD;
        }
        return response.getCertStatus();
    } catch (OCSPException e) {
        return new UnknownStatus();
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) Req(org.bouncycastle.cert.ocsp.Req) Arrays(java.util.Arrays) AccessDescription(org.bouncycastle.asn1.x509.AccessDescription) Enumeration(java.util.Enumeration) Extension(org.bouncycastle.asn1.x509.Extension) URISyntaxException(java.net.URISyntaxException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) LoggerFactory(org.slf4j.LoggerFactory) KeyStoreException(java.security.KeyStoreException) X500Name(org.bouncycastle.asn1.x500.X500Name) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) Map(java.util.Map) URI(java.net.URI) X509ExtensionUtil(org.bouncycastle.x509.extension.X509ExtensionUtil) ClientBuilderFactory(org.codice.ddf.cxf.client.ClientBuilderFactory) OcspService(org.codice.ddf.security.OcspService) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) NoticePriority(org.codice.ddf.system.alerts.NoticePriority) Set(java.util.Set) KeyStore(java.security.KeyStore) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) ClientBuilder(org.codice.ddf.cxf.client.ClientBuilder) PrivilegedAction(java.security.PrivilegedAction) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Response(javax.ws.rs.core.Response) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Entry(java.util.Map.Entry) ProcessingException(javax.ws.rs.ProcessingException) SecureCxfClientFactory(org.codice.ddf.cxf.client.SecureCxfClientFactory) AccessController(java.security.AccessController) Certificate(org.bouncycastle.asn1.x509.Certificate) CertificateEncodingException(java.security.cert.CertificateEncodingException) EventAdmin(org.osgi.service.event.EventAdmin) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) HashMap(java.util.HashMap) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) SecurityConstants(ddf.security.SecurityConstants) Nullable(javax.annotation.Nullable) DERIA5String(org.bouncycastle.asn1.DERIA5String) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) Logger(org.slf4j.Logger) SecurityLogger(ddf.security.audit.SecurityLogger) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) UnknownStatus(org.bouncycastle.cert.ocsp.UnknownStatus) WebClient(org.apache.cxf.jaxrs.client.WebClient) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) DigestCalculator(org.bouncycastle.operator.DigestCalculator) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) CertificateException(java.security.cert.CertificateException) BasicOCSPResponse(org.bouncycastle.asn1.ocsp.BasicOCSPResponse) SystemNotice(org.codice.ddf.system.alerts.SystemNotice) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Event(org.osgi.service.event.Event) InputStream(java.io.InputStream) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) UnknownStatus(org.bouncycastle.cert.ocsp.UnknownStatus)

Example 38 with Certificate

use of com.beanit.asn1bean.compiler.pkix1explicit88.Certificate in project ddf by codice.

the class OcspChecker method passesOcspCheck.

/**
 * Checks whether the given {@param certs} are revoked or not against the configured OCSP server
 * urls + the optionally given OCSP server url in the given {@param certs}.
 *
 * @param certs - an array of certificates to verify.
 * @return true if the certificates are good or if they could not be properly checked against the
 *     OCSP server. Returns false if any of them are revoked.
 */
@Override
public boolean passesOcspCheck(X509Certificate[] certs) {
    if (!ocspEnabled) {
        LOGGER.debug("OCSP check is not enabled. Skipping.");
        return true;
    }
    LOGGER.debug("OCSP check for {} certificate(s)", certs == null ? "0" : certs.length);
    for (X509Certificate cert : certs) {
        try {
            Certificate certificate = convertToBouncyCastleCert(cert);
            OCSPReq ocspRequest = generateOcspRequest(certificate);
            Map<URI, CertificateStatus> ocspStatuses = sendOcspRequests(cert, ocspRequest);
            URI revokedStatusUrl = getFirstRevokedStatusUrl(ocspStatuses);
            if (revokedStatusUrl != null) {
                securityLogger.audit("Certificate {} has been revoked by the OCSP server at URL {}.", cert, revokedStatusUrl);
                LOGGER.warn("Certificate {} has been revoked by the OCSP server at URL {}.", cert, revokedStatusUrl);
                return false;
            }
            LOGGER.debug("No certificates revoked by the OCSP server");
        } catch (OcspCheckerException e) {
            postErrorEvent(e.getMessage());
        }
    }
    // An alert will be posted to the admin console.
    return true;
}
Also used : OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) URI(java.net.URI) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 39 with Certificate

use of com.beanit.asn1bean.compiler.pkix1explicit88.Certificate in project jruby-openssl by jruby.

the class OCSPRequest method verify.

@JRubyMethod(name = "verify", rest = true)
public IRubyObject verify(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.runtime;
    int flags = 0;
    boolean ret = false;
    if (Arity.checkArgumentCount(runtime, args, 2, 3) == 3) {
        flags = RubyFixnum.fix2int((RubyFixnum) args[2]);
    }
    IRubyObject certificates = args[0];
    IRubyObject store = args[1];
    OCSPReq bcOCSPReq = getBCOCSPReq();
    if (bcOCSPReq == null) {
        throw newOCSPError(runtime, new NullPointerException("Missing BC asn1bcReq. Missing certIDs or signature?"));
    }
    if (!bcOCSPReq.isSigned()) {
        return RubyBoolean.newBoolean(runtime, ret);
    }
    GeneralName genName = bcOCSPReq.getRequestorName();
    if (genName.getTagNo() != 4) {
        return RubyBoolean.newBoolean(runtime, ret);
    }
    X500Name genX500Name = X500Name.getInstance(genName.getName());
    X509StoreContext storeContext;
    try {
        java.security.cert.Certificate signer = findCertByName(genX500Name, certificates, flags);
        if (signer == null)
            return RubyBoolean.newBoolean(runtime, ret);
        if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOINTERN))) > 0 && ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_TRUSTOTHER))) > 0))
            flags |= RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOVERIFY));
        if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOSIGS))) == 0) {
            PublicKey signerPubKey = signer.getPublicKey();
            ContentVerifierProvider cvp = newJcaContentVerifierProviderBuilder().build(signerPubKey);
            ret = bcOCSPReq.isSignatureValid(cvp);
            if (!ret) {
                return RubyBoolean.newBoolean(runtime, ret);
            }
        }
        if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOVERIFY))) == 0) {
            if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOCHAIN))) > 0) {
                storeContext = X509StoreContext.newStoreContext(context, (X509Store) store, X509Cert.wrap(runtime, signer), context.nil);
            } else {
                RubyArray certs = RubyArray.newEmptyArray(runtime);
                ASN1Sequence bcCerts = asn1bcReq.getOptionalSignature().getCerts();
                if (bcCerts != null) {
                    Iterator<ASN1Encodable> it = bcCerts.iterator();
                    while (it.hasNext()) {
                        Certificate cert = Certificate.getInstance(it.next());
                        certs.add(X509Cert.wrap(runtime, new X509AuxCertificate(cert)));
                    }
                }
                storeContext = X509StoreContext.newStoreContext(context, (X509Store) store, X509Cert.wrap(runtime, signer), certs);
            }
            storeContext.set_purpose(context, _X509(runtime).getConstant("PURPOSE_OCSP_HELPER"));
            storeContext.set_trust(context, _X509(runtime).getConstant("TRUST_OCSP_REQUEST"));
            ret = storeContext.verify(context).isTrue();
            if (!ret)
                return RubyBoolean.newBoolean(runtime, false);
        }
    } catch (Exception e) {
        debugStackTrace(e);
        throw newOCSPError(runtime, e);
    }
    return RubyBoolean.newBoolean(getRuntime(), ret);
}
Also used : RubyArray(org.jruby.RubyArray) PublicKey(java.security.PublicKey) X500Name(org.bouncycastle.asn1.x500.X500Name) IRubyObject(org.jruby.runtime.builtin.IRubyObject) RubyFixnum(org.jruby.RubyFixnum) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) X509AuxCertificate(org.jruby.ext.openssl.x509store.X509AuxCertificate) Ruby(org.jruby.Ruby) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) X509AuxCertificate(org.jruby.ext.openssl.x509store.X509AuxCertificate) JRubyMethod(org.jruby.anno.JRubyMethod)

Example 40 with Certificate

use of com.beanit.asn1bean.compiler.pkix1explicit88.Certificate in project open-ecard by ecsec.

the class ExpirationVerifier method isValid.

@Override
public void isValid(TlsServerCertificate chain, String hostOrIP) throws CertificateVerificationException {
    try {
        Date now = new Date();
        for (TlsCertificate next : chain.getCertificate().getCertificateList()) {
            Certificate c = Certificate.getInstance(next.getEncoded());
            Date expDate = c.getEndDate().getDate();
            if (now.after(expDate)) {
                String msg = String.format("The certificate '%s' expired at %s.", c.getSubject(), expDate);
                throw new CertificateVerificationException(msg);
            }
        }
    } catch (IOException ex) {
        throw new CertificateVerificationException("Invalid certificate received from server.", ex);
    }
}
Also used : CertificateVerificationException(org.openecard.crypto.tls.CertificateVerificationException) IOException(java.io.IOException) Date(java.util.Date) TlsCertificate(org.openecard.bouncycastle.tls.crypto.TlsCertificate) TlsServerCertificate(org.openecard.bouncycastle.tls.TlsServerCertificate) TlsCertificate(org.openecard.bouncycastle.tls.crypto.TlsCertificate) Certificate(org.openecard.bouncycastle.asn1.x509.Certificate)

Aggregations

Certificate (org.bouncycastle.asn1.x509.Certificate)53 IOException (java.io.IOException)40 X509Certificate (java.security.cert.X509Certificate)37 CertificateException (java.security.cert.CertificateException)27 File (java.io.File)11 Test (org.junit.Test)10 BigInteger (java.math.BigInteger)9 CertificateEncodingException (java.security.cert.CertificateEncodingException)9 TBSCertificate (org.bouncycastle.asn1.x509.TBSCertificate)9 Test (org.junit.jupiter.api.Test)9 Certificate (com.google.cloud.security.privateca.v1.Certificate)8 CertificateAuthorityServiceClient (com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient)8 SQLException (java.sql.SQLException)8 X500Name (org.bouncycastle.asn1.x500.X500Name)8 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)7 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)7 Certificate (com.beanit.asn1bean.compiler.pkix1explicit88.Certificate)6 Extension (org.bouncycastle.asn1.x509.Extension)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)6 Date (java.util.Date)5