Beispiel #1
0
 /// <summary>
 /// An X509Certificate may contain information about his issuer in the AIA attribute.
 /// </summary>
 public virtual ICertificateSource GetWrappedCertificateSource()
 {
     if (sourceFactory != null)
     {
         ICertificateSource source = sourceFactory.CreateAIACertificateSource(GetCertificate());
         return(source);
     }
     else
     {
         return(null);
     }
 }
Beispiel #2
0
        /// <summary>
        /// Validate the timestamp
        /// </summary>
        public virtual void ValidateTimestamp(TimestampToken timestamp, ICertificateSource optionalSource, ICrlSource optionalCRLSource, IOcspSource optionalOCPSSource, IList <CertificateAndContext> usedCerts)
        {
            if (timestamp is null)
            {
                throw new ArgumentNullException(nameof(timestamp));
            }

            AddNotYetVerifiedToken(timestamp);
            Validate(
                timestamp.GetTimeStamp().TimeStampInfo.GenTime,
                new CompositeCertificateSource(timestamp.GetWrappedCertificateSource(), optionalSource),
                optionalCRLSource,
                optionalOCPSSource,
                usedCerts);
        }
Beispiel #3
0
 /// <summary>
 /// The default constructor for ValidationContextV2.
 /// </summary>
 /// <param>
 /// The certificate that will be validated.
 /// </param>
 public ValidationContext(X509Certificate certificate, DateTime validationDate, ICAdESLogger cadesLogger, IOcspSource ocspSource, ICrlSource crlSource, ICertificateSource certificateSource, Func <IOcspSource, ICrlSource, ICertificateStatusVerifier> certificateVerifierFactory, Func <CertificateAndContext, CertificateToken> certificateTokenFactory)
 {
     this.certificateTokenFactory = certificateTokenFactory;
     OcspSource = ocspSource;
     CrlSource  = crlSource;
     TrustedListCertificatesSource = certificateSource;
     logger = cadesLogger;
     if (certificate != null)
     {
         logger?.Info("New context for " + certificate.SubjectDN);
         var trustedCert = TrustedListCertificatesSource?.GetCertificateBySubjectName(certificate.SubjectDN)?.FirstOrDefault();
         Certificate = certificate;
         AddNotYetVerifiedToken(certificateTokenFactory(trustedCert ?? new CertificateAndContext(certificate)));
     }
     ValidationDate = validationDate;
     this.certificateVerifierFactory = certificateVerifierFactory;
 }
        public virtual IValidationContext ValidateCertificate(
            X509Certificate cert, DateTime validationDate, ICertificateSource optionalCertificateSource, IList <CertificateAndContext> usedCerts, ICrlSource optionalCRLSource = null, IOcspSource optionalOCSPSource = null, ICAdESLogger CadesLogger = null)
        {
            if (cert == null || validationDate == null)
            {
                throw new ArgumentNullException("A validation context must contains a cert and a validation date");
            }

            var alreadyUsed = cache.FirstOrDefault(x => x.Certificate == cert && x.ValidationDate == validationDate);

            if (alreadyUsed != null)
            {
                return(alreadyUsed);
            }

            var context = validationContextFactory(cert, validationDate, CadesLogger);

            context.Validate(validationDate, optionalCertificateSource, optionalCRLSource, optionalOCSPSource, usedCerts);
            cache.Add(context);

            return(context);
        }
Beispiel #5
0
        private void CreateCertificate(CertificateTask task, ICertificateSource source, IEnumerable <CertificateFile> files)
        {
            var savedFiles = new List <CertificateFile>();

            using (var transaction = new TransactionScope(OnDispose.Rollback)) {
                var certificate = Certificate.Queryable.FirstOrDefault(
                    c => c.CatalogProduct.Id == task.CatalogProduct.Id && c.SerialNumber == task.SerialNumber);

                if (certificate == null)
                {
                    certificate = new Certificate {
                        CatalogProduct = task.CatalogProduct,
                        SerialNumber   = task.SerialNumber
                    };
                    _logger.DebugFormat("При обработке задачи {0} будет создан сертификат", task);
                }
                else
                {
                    _logger.DebugFormat("При обработке задачи {0} будет использоваться сертификат c Id:{1}", task, certificate.Id);
                }

                foreach (var file in files)
                {
                    file.CertificateSource = task.CertificateSource;
                    var exist = Find(file) ?? file;
                    certificate.NewFile(exist);
                    if (exist != file)
                    {
                        exist.LocalFile = file.LocalFile;
                        _logger.DebugFormat("При обработке задачи {0} будет использоваться файл сертификата {1}", task, exist);
                    }
                    else
                    {
                        _logger.DebugFormat("При обработке задачи {0} будет создан файл сертификата {1}", task, exist);
                    }
                    savedFiles.Add(exist);
                }

                certificate.Save();

                task.Delete();

                var session = ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(typeof(ActiveRecordBase));
                try {
                    session.CreateSQLQuery(@"
	update
		documents.Certificates c,
		catalogs.Products p,
		documents.DocumentBodies db
	set
		db.CertificateId = c.Id
	where
		c.Id = :certificateId
		and p.CatalogId = c.catalogId
		and db.ProductId is not null
		and db.SerialNumber is not null
		and db.ProductId = p.Id
		and db.SerialNumber = :serialNumber
		and db.CertificateId is null;
		"        )
                    .SetParameter("certificateId", certificate.Id)
                    .SetParameter("serialNumber", task.DocumentLine.SerialNumber)
                    .ExecuteUpdate();
                }
                finally {
                    ActiveRecordMediator.GetSessionFactoryHolder().ReleaseSession(session);
                }

                transaction.VoteCommit();
            }


            foreach (var file in savedFiles)
            {
                var fileName     = file.RemoteFile;
                var fullFileName = Path.Combine(Settings.Default.CertificatePath, fileName);

                try {
                    if (File.Exists(fullFileName))
                    {
                        File.Delete(fullFileName);
                        _logger.InfoFormat(
                            "Будет произведено обновление файла сертификата {0} с Id {1} для сертификата {2}",
                            file.LocalFile,
                            file.Id,
                            task);
                    }

                    File.Copy(file.LocalFile, fullFileName);
                }
                catch (Exception exception) {
                    _logger.WarnFormat(
                        "При копировании файла {0} для сертификата {1} возникла ошибка: {2}",
                        file.LocalFile,
                        task,
                        exception);
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// Build the validation context for the specific date
        /// </summary>
        public virtual void Validate(DateTime validationDate, ICertificateSource optionalSource, ICrlSource optionalCRLSource, IOcspSource optionalOCPSSource, IList <CertificateAndContext> usedCerts)
        {
            int          previousSize     = RevocationInfo.Count;
            int          previousVerified = VerifiedTokenCount();
            ISignedToken signedToken      = GetOneNotYetVerifiedToken();

            if (signedToken != null)
            {
                ICertificateSource    otherSource = new CompositeCertificateSource(signedToken.GetWrappedCertificateSource(), optionalSource);
                CertificateAndContext issuer      = GetIssuerCertificate(signedToken, otherSource, validationDate);
                RevocationData        data        = null;
                if (issuer == null)
                {
                    logger?.Warn("Don't found any issuer for token " + signedToken);
                    data = new RevocationData(signedToken);
                }
                else
                {
                    usedCerts?.Add(issuer);
                    AddNotYetVerifiedToken(certificateTokenFactory(issuer));
                    if (issuer.Certificate.SubjectDN.Equals(issuer.Certificate.IssuerDN))
                    {
                        ISignedToken   trustedToken     = certificateTokenFactory(issuer);
                        RevocationData noNeedToValidate = new RevocationData();
                        if (issuer.CertificateSource == CertificateSourceType.TRUSTED_LIST)
                        {
                            noNeedToValidate.SetRevocationData(CertificateSourceType.TRUSTED_LIST);
                        }
                        Validate(trustedToken, noNeedToValidate);
                    }
                    else if (issuer.CertificateSource == CertificateSourceType.TRUSTED_LIST)
                    {
                        ISignedToken   trustedToken     = certificateTokenFactory(issuer);
                        RevocationData noNeedToValidate = new RevocationData();
                        noNeedToValidate.SetRevocationData(CertificateSourceType.TRUSTED_LIST);
                        Validate(trustedToken, noNeedToValidate);
                    }
                    if (signedToken is CertificateToken)
                    {
                        CertificateToken  ct     = (CertificateToken)signedToken;
                        CertificateStatus status = GetCertificateValidity(ct.GetCertificateAndContext(), issuer, validationDate, optionalCRLSource, optionalOCPSSource);
                        data = new RevocationData(signedToken);
                        if (status != null)
                        {
                            data.SetRevocationData(status.StatusSource);
                            if (status.StatusSource is X509Crl)
                            {
                                AddNotYetVerifiedToken(new CRLToken((X509Crl)status.StatusSource));
                            }
                            else
                            {
                                if (status.StatusSource is BasicOcspResp)
                                {
                                    AddNotYetVerifiedToken(new OCSPRespToken((BasicOcspResp)status.StatusSource));
                                }
                            }
                        }
                        else
                        {
                            logger?.Warn("No status for " + signedToken);
                        }
                    }
                    else
                    {
                        if (signedToken is CRLToken || signedToken is OCSPRespToken || signedToken is TimestampToken)
                        {
                            data = new RevocationData(signedToken);
                            data.SetRevocationData(issuer);
                        }
                        else
                        {
                            throw new Exception("Not supported token type " + signedToken.GetType().Name);
                        }
                    }
                }
                Validate(signedToken, data);
                logger?.Info(ToString());
                int newSize     = RevocationInfo.Count;
                int newVerified = VerifiedTokenCount();
                if (newSize != previousSize || newVerified != previousVerified)
                {
                    Validate(validationDate, otherSource, optionalCRLSource, optionalOCPSSource, usedCerts);
                }
            }
        }
Beispiel #7
0
        internal virtual CertificateAndContext GetIssuerCertificate(ISignedToken signedToken, ICertificateSource optionalSource, DateTime validationDate)
        {
            if (signedToken.GetSignerSubjectName() == null)
            {
                return(null);
            }
            IList <CertificateAndContext> list = new CompositeCertificateSource(TrustedListCertificatesSource, optionalSource).GetCertificateBySubjectName(signedToken.GetSignerSubjectName());

            if (list != null)
            {
                foreach (CertificateAndContext cert in list)
                {
                    logger?.Info(cert.ToString());
                    if (validationDate != null)
                    {
                        try
                        {
                            cert.Certificate.CheckValidity(validationDate);
                        }
                        catch (CertificateExpiredException)
                        {
                            logger?.Info(WasExpiredMessage);
                            continue;
                        }
                        catch (CertificateNotYetValidException)
                        {
                            logger?.Info(WasNotYetValidMessage);
                            continue;
                        }
                        if (cert.CertificateSource == CertificateSourceType.TRUSTED_LIST && cert.Context != null)
                        {
                            ServiceInfo info = (ServiceInfo)cert.Context;
                            if (info.StatusStartingDateAtReferenceTime != null && validationDate.CompareTo( //jbonilla Before
                                    info.StatusStartingDateAtReferenceTime) < 0)
                            {
                                logger?.Info(WasNotValidTSLMessage);
                                continue;
                            }
                            else
                            {
                                if (info.StatusEndingDateAtReferenceTime != null && validationDate.CompareTo(info //jbonilla After
                                                                                                             .StatusEndingDateAtReferenceTime) > 0)
                                {
                                    logger?.Info(WasNotValidTSLMessage);
                                    continue;
                                }
                            }
                        }
                    }
                    if (signedToken.IsSignedBy(cert.Certificate))
                    {
                        return(cert);
                    }
                }
            }
            return(null);
        }
Beispiel #8
0
        private IDictionary ExtendUnsignedAttributes(IDictionary unsignedAttrs, X509Certificate signingCertificate, SignatureParameters parameters, DateTime signingTime, ICertificateSource optionalCertificateSource)
        {
            var usedCerts         = new List <CertificateAndContext>();
            var validationContext = CertificateVerifier.ValidateCertificate(
                signingCertificate,
                signingTime,
                new CompositeCertificateSource(new ListCertificateSource(parameters.CertificateChain), optionalCertificateSource), usedCerts);
            var completeCertificateRefs = new List <OtherCertID>();
            var completeRevocationRefs  = new List <CrlOcspRef>();

            foreach (CertificateAndContext c in validationContext.NeededCertificates)
            {
                if (!c.Equals(signingCertificate))
                {
                    completeCertificateRefs.Add(MakeOtherCertID(c.Certificate));
                }
                List <CrlValidatedID>  crlListIdValues  = new List <CrlValidatedID>();
                List <OcspResponsesID> ocspListIDValues = new List <OcspResponsesID>();
                foreach (X509Crl relatedcrl in validationContext.GetRelatedCRLs(c))
                {
                    crlListIdValues.Add(MakeCrlValidatedID(relatedcrl));
                }
                foreach (BasicOcspResp relatedocspresp in validationContext.GetRelatedOCSPResp(c))
                {
                    ocspListIDValues.Add(MakeOcspResponsesID(relatedocspresp));
                }
                completeRevocationRefs.Add(new CrlOcspRef(new CrlListID(crlListIdValues.ToArray()), new OcspListID(ocspListIDValues.ToArray()), null));
            }
            unsignedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsCertificateRefs, new BcCms.Attribute(PkcsObjectIdentifiers.IdAAEtsCertificateRefs, new DerSet(new DerSequence(completeCertificateRefs.ToArray()))));
            unsignedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsRevocationRefs, new BcCms.Attribute(PkcsObjectIdentifiers.IdAAEtsRevocationRefs, new DerSet(new DerSequence(completeRevocationRefs.ToArray()))));
            return(unsignedAttrs);
        }
Beispiel #9
0
        private IDictionary ExtendUnsignedAttributes(IDictionary unsignedAttrs, X509Certificate signingCertificate, DateTime signingDate, ICertificateSource optionalCertificateSource)
        {
            var validationContext = CertificateVerifier.ValidateCertificate(signingCertificate, signingDate, optionalCertificateSource, null, null);

            List <X509CertificateStructure> certificateValues = new List <X509CertificateStructure>();
            List <CertificateList>          crlValues         = new List <CertificateList>();
            List <BasicOcspResponse>        ocspValues        = new List <BasicOcspResponse>();

            foreach (CertificateAndContext c in validationContext.NeededCertificates)
            {
                if (!c.Equals(signingCertificate))
                {
                    certificateValues.Add(X509CertificateStructure.GetInstance(((Asn1Sequence)Asn1Object.FromByteArray(c.Certificate.GetEncoded()))));
                }
            }
            foreach (X509Crl relatedcrl in validationContext.NeededCRL)
            {
                crlValues.Add(CertificateList.GetInstance((Asn1Sequence)Asn1Object.FromByteArray(relatedcrl.GetEncoded())));
            }
            foreach (BasicOcspResp relatedocspresp in validationContext.NeededOCSPResp)
            {
                ocspValues.Add((BasicOcspResponse.GetInstance((Asn1Sequence)Asn1Object.FromByteArray(relatedocspresp.GetEncoded()))));
            }
            RevocationValues revocationValues = new RevocationValues(crlValues.ToArray(), ocspValues.ToArray(), null);

            unsignedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsRevocationValues, new BcCms.Attribute(PkcsObjectIdentifiers.IdAAEtsRevocationValues, new DerSet(revocationValues)));
            unsignedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsCertValues, new BcCms.Attribute(PkcsObjectIdentifiers.IdAAEtsCertValues, new DerSet(new DerSequence(certificateValues.ToArray()))));

            return(unsignedAttrs);
        }