Search in sources :

Example 1 with CertificateRevocationException

use of org.demoiselle.signer.core.exception.CertificateRevocationException in project signer by demoiselle.

the class XMLChecker method verifyCertificate.

private void verifyCertificate(X509Certificate varCert) {
    CRLValidator cV = new CRLValidator();
    try {
        cV.validate(varCert);
    } catch (CertificateValidatorCRLException cvce) {
        validationErrors.add(cvce.getMessage());
        logger.error(cvce.getMessage());
    } catch (CertificateRevocationException cre) {
        validationErrors.add(xadesMessagesBundle.getString("error.certificate.repealed", cre.getMessage()));
        logger.error("certificado revogado");
    }
    PeriodValidator pV = new PeriodValidator();
    try {
        pV.valDate(varCert);
    } catch (CertificateValidatorException cve) {
        validationWaring.add(cve.getMessage());
        logger.warn(cve.getMessage());
    }
}
Also used : CertificateValidatorException(org.demoiselle.signer.core.exception.CertificateValidatorException) CertificateValidatorCRLException(org.demoiselle.signer.core.exception.CertificateValidatorCRLException) CRLValidator(org.demoiselle.signer.core.validator.CRLValidator) PeriodValidator(org.demoiselle.signer.core.validator.PeriodValidator) CertificateRevocationException(org.demoiselle.signer.core.exception.CertificateRevocationException)

Example 2 with CertificateRevocationException

use of org.demoiselle.signer.core.exception.CertificateRevocationException in project signer by demoiselle.

the class CAdESChecker method check.

/**
 * Validation is done only on digital signatures with a single signer. Valid
 * only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 =
 * OID Data 1.2.840.113549.1.7.1
 *
 * @param content    Is only necessary to inform if the PKCS7 package is NOT
 *                   ATTACHED type. If it is of type attached, this parameter will be
 *                   replaced by the contents of the PKCS7 package.
 * @param signedData Value in bytes of the PKCS7 package, such as the
 *                   contents of a ".p7s" file. It is not only signature as in the
 *                   case of PKCS1.
 */
private boolean check(byte[] content, byte[] signedData) throws SignerException {
    Security.addProvider(new BouncyCastleProvider());
    CMSSignedData cmsSignedData = null;
    try {
        if (content == null) {
            if (this.checkHash) {
                cmsSignedData = new CMSSignedData(this.hashes, signedData);
                this.checkHash = false;
            } else {
                cmsSignedData = new CMSSignedData(signedData);
            }
        } else {
            if (this.getAttached(signedData, false).getExtractedContent() != null) {
                cmsSignedData = new CMSSignedData(signedData);
            } else {
                cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData);
            }
        }
    } catch (CMSException ex) {
        logger.error(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7") + ex.getMessage());
        throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex);
    }
    // Quantidade inicial de assinaturas validadas
    int verified = 0;
    Store<?> certStore = cmsSignedData.getCertificates();
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    Iterator<?> it = signers.getSigners().iterator();
    // Realização da verificação básica de todas as assinaturas
    while (it.hasNext()) {
        SignatureInformations signatureInfo = new SignatureInformations();
        try {
            SignerInformation signerInfo = (SignerInformation) it.next();
            SignerInformationStore signerInfoStore = signerInfo.getCounterSignatures();
            if (signerInfoStore.size() > 0) {
                logger.info(cadesMessagesBundle.getString("info.co.signature", signerInfoStore.size()));
            }
            @SuppressWarnings("unchecked") Collection<?> certCollection = certStore.getMatches(signerInfo.getSID());
            Iterator<?> certIt = certCollection.iterator();
            X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next();
            X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
            CRLValidator cV = new CRLValidator();
            try {
                cV.validate(varCert);
            } catch (CertificateValidatorCRLException cvce) {
                signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.crl.not.access", cvce.getMessage()));
                logger.debug(cadesMessagesBundle.getString("error.crl.not.access", cvce.getMessage()));
            } catch (CertificateRevocationException cre) {
                signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.crl.not.access", cre.getMessage()));
                logger.error(cadesMessagesBundle.getString("error.crl.not.access", cre.getMessage()));
            }
            PeriodValidator pV = new PeriodValidator();
            try {
                signatureInfo.setNotAfter(pV.valDate(varCert));
            } catch (CertificateValidatorException cve) {
                signatureInfo.getValidatorWarnins().add(cve.getMessage());
                logger.error(cve.getMessage());
            }
            try {
                if (signerInfo.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) {
                    verified++;
                    logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified));
                } else {
                    signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.invalid.signature", "Erro de verificação!"));
                    signatureInfo.setInvalidSignature(true);
                }
            } catch (CMSVerifierCertificateNotValidException e) {
                signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.invalid.signature", e.getMessage()));
                signatureInfo.setInvalidSignature(true);
            }
            // recupera atributos assinados
            logger.debug(cadesMessagesBundle.getString("info.signed.attribute"));
            String varOIDPolicy = PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId();
            AttributeTable signedAttributes = signerInfo.getSignedAttributes();
            if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) {
                signatureInfo.getValidatorWarnins().add(cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
                logger.warn(cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
            // throw new SignerException(cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
            } else {
                // Validando atributos assinados de acordo com a politica
                Attribute idSigningPolicy = null;
                idSigningPolicy = signedAttributes.get(new ASN1ObjectIdentifier(varOIDPolicy));
                if (idSigningPolicy == null) {
                    signatureInfo.getValidatorWarnins().add(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", varOIDPolicy));
                } else {
                    for (Enumeration<?> p = idSigningPolicy.getAttrValues().getObjects(); p.hasMoreElements(); ) {
                        String policyOnSignature = p.nextElement().toString();
                        for (PolicyFactory.Policies pv : PolicyFactory.Policies.values()) {
                            if (policyOnSignature.contains(pv.getUrl())) {
                                setSignaturePolicy(pv);
                                break;
                            }
                        }
                    }
                }
            }
            Date dataHora = null;
            if (signedAttributes != null) {
                // Valida o atributo ContentType
                Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType);
                if (attributeContentType == null) {
                    signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType"));
                    logger.info(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType"));
                    throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType"));
                }
                if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) {
                    signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.content.not.data"));
                    logger.info(cadesMessagesBundle.getString("error.content.not.data"));
                    throw new SignerException(cadesMessagesBundle.getString("error.content.not.data"));
                }
                // Validando o atributo MessageDigest
                Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest);
                if (attributeMessageDigest == null) {
                    logger.info(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest"));
                    throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest"));
                }
                // Mostra data e  hora da assinatura, não é carimbo de tempo
                Attribute timeAttribute = signedAttributes.get(CMSAttributes.signingTime);
                if (timeAttribute != null) {
                    TimeZone.setDefault(null);
                    dataHora = (((ASN1UTCTime) timeAttribute.getAttrValues().getObjectAt(0)).getDate());
                    logger.debug(cadesMessagesBundle.getString("info.date.utc", dataHora));
                } else {
                    logger.debug(cadesMessagesBundle.getString("info.date.utc", "N/D"));
                }
            }
            if (signaturePolicy == null) {
                signatureInfo.getValidatorWarnins().add(cadesMessagesBundle.getString("error.policy.on.component.not.found", varOIDPolicy));
                logger.debug(cadesMessagesBundle.getString("error.policy.on.component.not.found"));
            } else {
                if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr().getObjectIdentifiers() != null) {
                    for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr().getObjectIdentifiers()) {
                        String oi = objectIdentifier.getValue();
                        Attribute signedAtt = signedAttributes.get(new ASN1ObjectIdentifier(oi));
                        logger.debug(oi);
                        if (signedAtt == null) {
                            logger.debug(cadesMessagesBundle.getString("error.signed.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue()));
                            signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.signed.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue()));
                        }
                    }
                }
            }
            // recupera os atributos NÃO assinados
            logger.debug(cadesMessagesBundle.getString("info.unsigned.attribute"));
            AttributeTable unsignedAttributes = signerInfo.getUnsignedAttributes();
            if ((unsignedAttributes == null) || (unsignedAttributes != null && unsignedAttributes.size() == 0)) {
                // Apenas info pois a RB não tem atributos não assinados
                logger.debug(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found"));
            }
            if (signaturePolicy != null) {
                // Validando atributos NÃO assinados de acordo com a politica
                if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers() != null) {
                    for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers()) {
                        String oi = objectIdentifier.getValue();
                        Attribute unSignedAtt = unsignedAttributes.get(new ASN1ObjectIdentifier(oi));
                        logger.debug(oi);
                        if (unSignedAtt == null) {
                            logger.debug(cadesMessagesBundle.getString("error.signed.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue()));
                            signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.unsigned.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue()));
                        }
                        if (oi.equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) {
                            // Verificando timeStamp
                            try {
                                byte[] varSignature = signerInfo.getSignature();
                                Timestamp varTimeStampSigner = validateTimestamp(unSignedAtt, varSignature);
                                signatureInfo.setTimeStampSigner(varTimeStampSigner);
                            } catch (Exception ex) {
                                logger.info(ex.getMessage());
                                signatureInfo.getValidatorErrors().add(ex.getMessage());
                            // nas assinaturas feitas na applet o unsignedAttributes.get gera exceção.
                            }
                        }
                        if (oi.equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) {
                            logger.info("++++++++++  EscTimeStamp ++++++++++++");
                        }
                    }
                }
            }
            LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance().getCertificateChain(varCert);
            // menor que 2 = autoAssinado
            if (varChain.size() < 2) {
                signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN()));
                logger.info(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN()));
            }
            for (X509Certificate cert : varChain) {
                BasicCertificate signerCertificate = new BasicCertificate(cert);
                if (!signerCertificate.isCACertificate()) {
                    signatureInfo.setIcpBrasilcertificate(signerCertificate);
                }
            }
            signatureInfo.setSignDate(dataHora);
            signatureInfo.setChain(varChain);
            signatureInfo.setSignaturePolicy(signaturePolicy);
            this.getSignaturesInfo().add(signatureInfo);
        } catch (OperatorCreationException | java.security.cert.CertificateException ex) {
            signatureInfo.getValidatorErrors().add(ex.getMessage());
            logger.info(ex.getMessage());
        } catch (CMSException ex) {
            // When file is mismatch with sign
            if (ex instanceof CMSSignerDigestMismatchException) {
                signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.signature.mismatch"));
                logger.info(cadesMessagesBundle.getString("error.signature.mismatch"));
                throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex);
            } else {
                signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.signature.invalid", ex.getMessage()));
                logger.info(cadesMessagesBundle.getString("error.signature.invalid", ex.getMessage()));
                throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid", ex.getMessage()), ex);
            }
        } catch (ParseException e) {
            signatureInfo.getValidatorErrors().add(e.getMessage());
            logger.info(e.getMessage());
        }
    }
    logger.debug(cadesMessagesBundle.getString("info.signature.verified", verified));
    // TODO Efetuar o parsing da estrutura CMS
    return true;
}
Also used : PolicyFactory(org.demoiselle.signer.policy.engine.factory.PolicyFactory) Attribute(org.bouncycastle.asn1.cms.Attribute) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) ASN1UTCTime(org.bouncycastle.asn1.ASN1UTCTime) SignerInformation(org.bouncycastle.cms.SignerInformation) CRLValidator(org.demoiselle.signer.core.validator.CRLValidator) Timestamp(org.demoiselle.signer.timestamp.Timestamp) CertificateRevocationException(org.demoiselle.signer.core.exception.CertificateRevocationException) SignatureInformations(org.demoiselle.signer.policy.impl.cades.SignatureInformations) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) PeriodValidator(org.demoiselle.signer.core.validator.PeriodValidator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) ObjectIdentifier(org.demoiselle.signer.policy.engine.asn1.etsi.ObjectIdentifier) CMSSignerDigestMismatchException(org.bouncycastle.cms.CMSSignerDigestMismatchException) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) CMSVerifierCertificateNotValidException(org.bouncycastle.cms.CMSVerifierCertificateNotValidException) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CertificateValidatorCRLException(org.demoiselle.signer.core.exception.CertificateValidatorCRLException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) CertificateValidatorException(org.demoiselle.signer.core.exception.CertificateValidatorException) ParseException(java.text.ParseException) TSPException(org.bouncycastle.tsp.TSPException) CertificateRevocationException(org.demoiselle.signer.core.exception.CertificateRevocationException) CMSVerifierCertificateNotValidException(org.bouncycastle.cms.CMSVerifierCertificateNotValidException) CMSException(org.bouncycastle.cms.CMSException) CertificateValidatorCRLException(org.demoiselle.signer.core.exception.CertificateValidatorCRLException) CMSSignerDigestMismatchException(org.bouncycastle.cms.CMSSignerDigestMismatchException) IOException(java.io.IOException) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) LinkedList(java.util.LinkedList) BasicCertificate(org.demoiselle.signer.core.extension.BasicCertificate) CertificateValidatorException(org.demoiselle.signer.core.exception.CertificateValidatorException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ParseException(java.text.ParseException) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

CertificateRevocationException (org.demoiselle.signer.core.exception.CertificateRevocationException)2 CertificateValidatorCRLException (org.demoiselle.signer.core.exception.CertificateValidatorCRLException)2 CertificateValidatorException (org.demoiselle.signer.core.exception.CertificateValidatorException)2 CRLValidator (org.demoiselle.signer.core.validator.CRLValidator)2 PeriodValidator (org.demoiselle.signer.core.validator.PeriodValidator)2 IOException (java.io.IOException)1 X509Certificate (java.security.cert.X509Certificate)1 ParseException (java.text.ParseException)1 Date (java.util.Date)1 LinkedList (java.util.LinkedList)1 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)1 ASN1UTCTime (org.bouncycastle.asn1.ASN1UTCTime)1 Attribute (org.bouncycastle.asn1.cms.Attribute)1 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)1 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)1 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)1 CMSException (org.bouncycastle.cms.CMSException)1 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)1 CMSSignedData (org.bouncycastle.cms.CMSSignedData)1 CMSSignerDigestMismatchException (org.bouncycastle.cms.CMSSignerDigestMismatchException)1