private static bool VerificaNonRepudiation(EsitoVerifica ev, bool fileOK, Org.BouncyCastle.X509.X509Certificate cert1) { /* * digitalSignature (0), * nonRepudiation (1), * keyEncipherment (2), * dataEncipherment (3), * keyAgreement (4), * keyCertSign (5), * cRLSign (6), * encipherOnly (7), * decipherOnly (8) */ try { bool[] keyUsageBA = cert1.GetKeyUsage(); if (!keyUsageBA[1]) // Manca la no repudiation non va bene per i file firmati!!! { fileOK = false; ev.status = EsitoVerificaStatus.ErroreGenerico; ev.message = "La chiave certificata non e abilitata alla firma"; ev.errorCode = "1409"; } } catch { } return(fileOK); }
/// <summary> /// Validates the cert with the provided crl responses. /// </summary> /// <param name="certificate">The cert to validate</param> /// <param name="issuer">The issuer of the cert to validate</param> /// <param name="validationTime">The time on which the cert was needed to validated</param> /// <param name="certLists">The list of crls to use</param> /// <returns>The crl response that was used, <c>null</c> if none used</returns> /// <exception cref="RevocationException{T}">When the certificate was revoked on the provided time</exception> /// <exception cref="RevocationUnknownException">When the certificate (or the crl) can't be validated</exception> public static BCAX.CertificateList Verify(this X509Certificate2 certificate, X509Certificate2 issuer, DateTime validationTime, IList <BCAX.CertificateList> certLists) { DateTime minTime = validationTime - ClockSkewness; DateTime maxTime = validationTime + ClockSkewness; BCX.X509Certificate certificateBC = DotNetUtilities.FromX509Certificate(certificate); BCX.X509Certificate issuerBC = DotNetUtilities.FromX509Certificate(issuer); ValueWithRef <BCX.X509Crl, BCAX.CertificateList> crlWithOrg = certLists .Select((c) => new ValueWithRef <BCX.X509Crl, BCAX.CertificateList>(new BCX.X509Crl(c), c)) //convert, keep orginal .Where((c) => c.Value.IssuerDN.Equals(certificateBC.IssuerDN)) .Where((c) => c.Value.ThisUpdate >= minTime || (c.Value.NextUpdate != null && c.Value.NextUpdate.Value >= minTime)) .OrderByDescending((c) => c.Value.ThisUpdate) .FirstOrDefault(); if (crlWithOrg == null) { return(null); } BCX.X509Crl crl = crlWithOrg.Value; BCAX.CertificateList certList = crlWithOrg.Reference; //check the signature (no need the check the issuer here) try { crl.Verify(issuerBC.GetPublicKey()); } catch (Exception e) { throw new RevocationUnknownException("The CRL has an invalid signature", e); } //check the signer (only the part relevant for CRL) if (!issuerBC.GetKeyUsage()[6]) { throw new RevocationUnknownException("The CRL was signed with a certificate that isn't allowed to sign CRLs"); } //check if the certificate is revoked BCX.X509CrlEntry crlEntry = crl.GetRevokedCertificate(certificateBC.SerialNumber); if (crlEntry != null) { trace.TraceEvent(TraceEventType.Verbose, 0, "CRL indicates that {0} is revoked on {1}", certificate.Subject, crlEntry.RevocationDate); if (maxTime >= crlEntry.RevocationDate) { throw new RevocationException <BCAX.CertificateList>(certList, "The certificate was revoked on " + crlEntry.RevocationDate.ToString("o")); } } return(certList); }
internal static bool HasUnsupportedCriticalExtension(X509Certificate cert) { if (cert == null) { throw new ArgumentException("X509Certificate can't be null."); } foreach (String oid in cert.GetCriticalExtensionOids()) { if (oid == X509Extensions.BasicConstraints.Id || oid == X509Extensions.CertificatePolicies.Id || oid == X509Extensions.CrlDistributionPoints.Id || oid == X509Extensions.DeltaCrlIndicator.Id || oid == X509Extensions.InhibitAnyPolicy.Id || oid == X509Extensions.IssuingDistributionPoint.Id || oid == X509Extensions.NameConstraints.Id || oid == X509Extensions.PolicyConstraints.Id || oid == X509Extensions.PolicyMappings.Id || oid == X509Extensions.SubjectAlternativeName.Id) { continue; } if (oid == X509Extensions.KeyUsage.Id) { bool[] keyUsageFlags = cert.GetKeyUsage(); if (keyUsageFlags[KEY_USAGE_DIGITAL_SIGNATURE] || keyUsageFlags[KEY_USAGE_NON_REPUDIATION]) { continue; } } try { // EXTENDED KEY USAGE and TIMESTAMPING is ALLOWED if (oid == X509Extensions.ExtendedKeyUsage.Id && cert.GetExtendedKeyUsage().Contains(OID.X509Extensions.ID_KP_TIMESTAMPING)) { continue; } } catch (CertificateParsingException) { // DO NOTHING; } return(true); } return(false); }
/** * Verifies a single certificate. * @param cert the certificate to verify * @param crls the certificate revocation list or <CODE>null</CODE> * @param calendar the date or <CODE>null</CODE> for the current date * @return a <CODE>String</CODE> with the error description or <CODE>null</CODE> * if no error */ public static String VerifyCertificate(X509Certificate cert, ICollection<X509Crl> crls, DateTime calendar) { foreach (String oid in cert.GetCriticalExtensionOids()) { // KEY USAGE and DIGITAL SIGNING is ALLOWED if ("2.5.29.15".Equals(oid) && cert.GetKeyUsage()[0]) { continue; } try { // EXTENDED KEY USAGE and TIMESTAMPING is ALLOWED if ("2.5.29.37".Equals(oid) && cert.GetExtendedKeyUsage().Contains("1.3.6.1.5.5.7.3.8")) { continue; } } catch (CertificateParsingException) { // DO NOTHING; } return "Has unsupported critical extension"; } try { if (!cert.IsValid(calendar)) return "The certificate has expired or is not yet valid"; if (crls != null) { foreach (X509Crl crl in crls) { if (crl.IsRevoked(cert)) return "Certificate revoked"; } } } catch (Exception e) { return e.ToString(); } return null; }
internal static void ProcessAttrCert3( X509Certificate acIssuerCert, PkixParameters pkixParams) { if (acIssuerCert.GetKeyUsage() != null && (!acIssuerCert.GetKeyUsage()[0] && !acIssuerCert.GetKeyUsage()[1])) { throw new PkixCertPathValidatorException( "Attribute certificate issuer public key cannot be used to validate digital signatures."); } if (acIssuerCert.GetBasicConstraints() != -1) { throw new PkixCertPathValidatorException( "Attribute certificate issuer is also a public key certificate issuer."); } }
private bool IsCRLOK(X509Crl x509crl, X509Certificate issuerCertificate, DateTime validationDate) { if (issuerCertificate == null) { throw new ArgumentNullException("Must provide a issuer certificate to validate the signature" ); } if (!x509crl.IssuerDN.Equals(issuerCertificate.SubjectDN)) { LOG.Warn("The CRL must be signed by the issuer (" + issuerCertificate.SubjectDN + " ) but instead is signed by " + x509crl.IssuerDN); return false; } try { x509crl.Verify(issuerCertificate.GetPublicKey()); } catch (Exception e) { LOG.Warn("The signature verification for CRL cannot be performed : " + e.Message ); return false; } DateTime thisUpdate = x509crl.ThisUpdate; LOG.Info("validation date: " + validationDate); LOG.Info("CRL this update: " + thisUpdate); // if (thisUpdate.after(validationDate)) { // LOG.warning("CRL too young"); // return false; // } LOG.Info("CRL next update: " + x509crl.NextUpdate); if (x509crl.NextUpdate != null && validationDate.CompareTo(x509crl.NextUpdate.Value) > 0) //jbonilla After { LOG.Info("CRL too old"); return false; } // assert cRLSign KeyUsage bit if (null == issuerCertificate.GetKeyUsage()) { LOG.Warn("No KeyUsage extension for CRL issuing certificate"); return false; } if (false == issuerCertificate.GetKeyUsage()[6]) { LOG.Warn("cRLSign bit not set for CRL issuing certificate"); return false; } return true; }
public static CertificateSecurityInformation Verify(this Org.BouncyCastle.X509.X509Certificate cert, DateTime date, int[] keyUsageIndexes, int minimumKeySize, IX509Store certs, ref IList <CertificateList> crls, ref IList <BasicOcspResponse> ocsps) { CertificateSecurityInformation result = new CertificateSecurityInformation(); result.Certificate = new X509Certificate2(cert.GetEncoded()); //check key size AsymmetricKeyParameter key = cert.GetPublicKey(); if (!VerifyKeySize(key, minimumKeySize)) { result.securityViolations.Add(CertSecurityViolation.NotValidKeySize); trace.TraceEvent(TraceEventType.Warning, 0, "The key was smaller then {0}", minimumKeySize); } //check key usages foreach (int i in keyUsageIndexes) { if (!cert.GetKeyUsage()[i]) { result.securityViolations.Add(CertSecurityViolation.NotValidForUsage); trace.TraceEvent(TraceEventType.Warning, 0, "The key usage did not have the correct usage flag {0} set", i); } } //build extra store X509Certificate2Collection extraStore = new X509Certificate2Collection(); foreach (Org.BouncyCastle.X509.X509Certificate obj in certs.GetMatches(null)) { extraStore.Add(new X509Certificate2(obj.GetEncoded())); } CertificateSecurityInformation dest = result; CertificateSecurityInformation previous = null; Org.BouncyCastle.X509.X509Certificate issuer = cert.ValidateAndGetDerivedIssuer(certs); if (issuer != null) { trace.TraceEvent(TraceEventType.Verbose, 0, "Detected eHealth variant of proxy certificate"); //check proxy certificate, is it still valid? if (!cert.IsValid(date)) { dest.securityViolations.Add(CertSecurityViolation.NotTimeValid); trace.TraceEvent(TraceEventType.Warning, 0, "The proxy certificate is expired or not yet valid, {0} not between {1}-{2}", date, cert.NotBefore, cert.NotAfter); } //The issuer signature of the proxy certificate is already checked... //check issuer previous = dest; dest = new CertificateSecurityInformation(); dest.Certificate = new X509Certificate2(issuer.GetEncoded()); //check key size of the issuer key = issuer.GetPublicKey(); if (!VerifyKeySize(key, minimumKeySize)) { dest.securityViolations.Add(CertSecurityViolation.NotValidKeySize); trace.TraceEvent(TraceEventType.Warning, 0, "The key of the issuer was smaller then {0}", minimumKeySize); } //check key usage of the issuer foreach (int i in new int[] { 0, 1 }) { if (!issuer.GetKeyUsage()[i]) { dest.securityViolations.Add(CertSecurityViolation.NotValidForUsage); trace.TraceEvent(TraceEventType.Warning, 0, "The key usage of the issuer did not have the correct usage flag set"); } } } //check the chain Chain chain; if (crls != null || ocsps != null) { chain = dest.Certificate.BuildChain(date, extraStore, crls, ocsps); } else { chain = dest.Certificate.BuildChain(date, extraStore); } //process the chain foreach (ChainElement ce in chain.ChainElements) { //connect the prepared link if (previous != null) { previous.IssuerInfo = dest; } //update the link dest.Certificate = ce.Certificate; foreach (X509ChainStatus status in ce.ChainElementStatus.Where(x => x.Status != X509ChainStatusFlags.NoError)) { dest.securityViolations.Add((CertSecurityViolation)Enum.Parse(typeof(CertSecurityViolation), Enum.GetName(typeof(X509ChainStatusFlags), status.Status))); } //prepare the next link previous = dest; dest = new CertificateSecurityInformation(); } if (chain.ChainStatus.Count(x => x.Status == X509ChainStatusFlags.PartialChain) > 0) { result.securityViolations.Add(CertSecurityViolation.IssuerTrustUnknown); } trace.TraceEvent(TraceEventType.Verbose, 0, "Verified certificate {0} for date {1}", cert.SubjectDN.ToString(), date); return(result); }
private bool GetKeyUsage(KeyUsageIndex index) => HasKeyUsage && _bcX509.GetKeyUsage()[(int)index];