/// <summary> /// Finds a certificate in a store. /// </summary> /// <param name="needPrivateKey">if set to <c>true</c> the returned certificate must contain the private key.</param> /// <returns>An instance of the <see cref="X509Certificate2"/> that is emebeded by this instance or find it in /// the selected strore pointed out by the <see cref="StorePath"/> using selected <see cref="SubjectName"/>.</returns> public async Task <X509Certificate2> Find(bool needPrivateKey) { X509Certificate2 certificate = null; // check if the entire certificate has been specified. if (m_certificate != null) { certificate = m_certificate; } else { // open store. ICertificateStore store = CertificateStoreIdentifier.PickStore(StoreType); store.Open(StorePath); X509Certificate2Collection collection = await store.Enumerate(); certificate = Find(collection, m_thumbprint, m_subjectName, needPrivateKey); if (certificate != null) { m_certificate = certificate; } } return(certificate); }
private bool EraseStore(string storePath) { bool result = true; try { using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(storePath)) { var storeCerts = store.Enumerate().Result; foreach (var cert in storeCerts) { if (!store.Delete(cert.Thumbprint).Result) { result = false; } } var storeCrls = store.EnumerateCRLs(); foreach (var crl in storeCrls) { if (!store.DeleteCRL(crl)) { result = false; } } } } catch { result = false; } return(result); }
/// <summary> /// Finds a certificate in a store. /// </summary> /// <param name="needPrivateKey">if set to <c>true</c> the returned certificate must contain the private key.</param> /// <returns>An instance of the <see cref="X509Certificate2"/> that is emebeded by this instance or find it in /// the selected strore pointed out by the <see cref="StorePath"/> using selected <see cref="SubjectName"/>.</returns> public async Task <X509Certificate2> Find(bool needPrivateKey) { X509Certificate2 certificate = null; // check if the entire certificate has been specified. if (m_certificate != null && (!needPrivateKey || m_certificate.HasPrivateKey)) { certificate = m_certificate; } else { // open store. using (ICertificateStore store = CertificateStoreIdentifier.CreateStore(StoreType)) { store.Open(StorePath); X509Certificate2Collection collection = await store.Enumerate(); certificate = Find(collection, m_thumbprint, m_subjectName, needPrivateKey); if (certificate != null) { m_certificate = certificate; } } } // use the single instance in the certificate cache. if (needPrivateKey) { certificate = m_certificate = CertificateFactory.Load(certificate, true); } return(certificate); }
protected async Task UpdateGroupStore(string storePath, X509Certificate2Collection certs, IList <Opc.Ua.X509CRL> crls) { if (!String.IsNullOrEmpty(storePath)) { using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(storePath)) { X509Certificate2Collection oldCertificates = await store.Enumerate(); foreach (var cert in oldCertificates) { await store.Delete(cert.Thumbprint); } foreach (var crl in store.EnumerateCRLs()) { store.DeleteCRL(crl); } foreach (var cert in certs) { await store.Add(cert); } foreach (var crl in crls) { store.AddCRL(crl); } } } }
public async Task <X509Certificate2Collection> GetCertificates() { X509Certificate2Collection collection = new X509Certificate2Collection(); if (!String.IsNullOrEmpty(this.StorePath)) { ICertificateStore store = null; try { store = OpenStore(); collection = await store.Enumerate().ConfigureAwait(false); } catch (Exception) { Utils.LogError("Could not load certificates from store: {0}.", this.StorePath); } finally { store?.Close(); } } foreach (CertificateIdentifier trustedCertificate in TrustedCertificates) { X509Certificate2 certificate = await trustedCertificate.Find().ConfigureAwait(false); if (certificate != null) { collection.Add(certificate); } } return(collection); }
/// <summary> /// Displays the applications in the control. /// </summary> internal void Initialize(CertificateStoreIdentifier id, IList <string> thumbprints) { ItemsLV.Items.Clear(); m_storeId = id; m_thumbprints = thumbprints; if (m_storeId == null || String.IsNullOrEmpty(m_storeId.StoreType) || String.IsNullOrEmpty(m_storeId.StorePath)) { Instructions = "No certificates are in the store."; AdjustColumns(); return; } try { // get the store. using (ICertificateStore store = m_storeId.OpenStore()) { // only show certificates with the specified thumbprint. if (thumbprints != null) { Instructions = "None of the selected certificates can be found in the store."; foreach (string thumbprint in thumbprints) { X509Certificate2 certificate = store.FindByThumbprint(thumbprint); if (certificate != null) { AddItem(certificate); } } } // show all certificates. else { Instructions = "No certificates are in the store."; foreach (X509Certificate2 certificate in store.Enumerate()) { AddItem(certificate); } } } } catch (Exception e) { Instructions = "An error occurred opening the store: " + e.Message; } // save the unfiltered list. m_items = new List <ListViewItem>(ItemsLV.Items.Count); foreach (ListViewItem item in ItemsLV.Items) { m_items.Add(item); } AdjustColumns(); }
private async void DeleteExistingFromStore(string storePath) { if (String.IsNullOrEmpty(storePath)) { return; } using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(storePath)) { X509Certificate2Collection certificates = await store.Enumerate(); foreach (var certificate in certificates) { if (store.GetPrivateKeyFilePath(certificate.Thumbprint) != null) { continue; } List <string> fields = Utils.ParseDistinguishedName(certificate.Subject); if (fields.Contains("CN=UA Local Discovery Server")) { continue; } DirectoryCertificateStore ds = store as DirectoryCertificateStore; if (ds != null) { string path = Utils.GetAbsoluteFilePath(m_application.CertificatePublicKeyPath, true, false, false); if (path != null) { if (String.Compare(path, ds.GetPublicKeyFilePath(certificate.Thumbprint), StringComparison.OrdinalIgnoreCase) == 0) { continue; } } path = Utils.GetAbsoluteFilePath(m_application.CertificatePrivateKeyPath, true, false, false); if (path != null) { if (String.Compare(path, ds.GetPrivateKeyFilePath(certificate.Thumbprint), StringComparison.OrdinalIgnoreCase) == 0) { continue; } } } await store.Delete(certificate.Thumbprint); } } }
public virtual async Task Init() { Utils.Trace(Utils.TraceMasks.Information, "InitializeCertificateGroup: {0}", m_subjectName); using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(m_authoritiesStorePath)) { X509Certificate2Collection certificates = await store.Enumerate(); foreach (var certificate in certificates) { if (Utils.CompareDistinguishedName(certificate.Subject, m_subjectName)) { using (RSA rsa = certificate.GetRSAPublicKey()) { if (rsa.KeySize != Configuration.CACertificateKeySize) { continue; } // TODO check hash size } if (Certificate != null) { // always use latest issued cert in store if (certificate.NotBefore > DateTime.UtcNow || Certificate.NotBefore > certificate.NotBefore) { continue; } } Certificate = certificate; } } } if (Certificate == null) { Utils.Trace(Utils.TraceMasks.Security, "Create new CA Certificate: {0}, KeySize: {1}, HashSize: {2}, LifeTime: {3} months", m_subjectName, Configuration.CACertificateKeySize, Configuration.CACertificateHashSize, Configuration.CACertificateLifetime ); X509Certificate2 newCertificate = await CreateCACertificateAsync(m_subjectName); Certificate = new X509Certificate2(newCertificate.RawData); } }
/// <summary> /// Get the certificate by issuer and serial number. /// </summary> private static async Task <X509Certificate2> FindIssuerCABySerialNumberAsync( ICertificateStore store, string issuer, string serialnumber) { X509Certificate2Collection certificates = await store.Enumerate(); foreach (var certificate in certificates) { if (Utils.CompareDistinguishedName(certificate.Subject, issuer) && Utils.IsEqual(certificate.SerialNumber, serialnumber)) { return(certificate); } } return(null); }
public static void CleanupTrustList(ICertificateStore store, bool dispose = true) { var certs = store.Enumerate().Result; foreach (var cert in certs) { store.Delete(cert.Thumbprint); } var crls = store.EnumerateCRLs(); foreach (var crl in crls) { store.DeleteCRL(crl); } if (dispose) { store.Dispose(); } }
/// <summary> /// Finds a certificate in a store. /// </summary> /// <param name="needPrivateKey">if set to <c>true</c> the returned certificate must contain the private key.</param> /// <returns>An instance of the <see cref="X509Certificate2"/> that is embedded by this instance or find it in /// the selected store pointed out by the <see cref="StorePath"/> using selected <see cref="SubjectName"/>.</returns> public async Task <X509Certificate2> Find(bool needPrivateKey) { X509Certificate2 certificate = null; // check if the entire certificate has been specified. if (m_certificate != null && (!needPrivateKey || m_certificate.HasPrivateKey)) { certificate = m_certificate; } else { // open store. using (ICertificateStore store = CertificateStoreIdentifier.CreateStore(StoreType)) { store.Open(StorePath, false); X509Certificate2Collection collection = await store.Enumerate().ConfigureAwait(false); certificate = Find(collection, m_thumbprint, m_subjectName, needPrivateKey); if (certificate != null) { if (needPrivateKey && store.SupportsLoadPrivateKey) { var message = new StringBuilder(); message.AppendLine("Loaded a certificate with private key from store {0}."); message.AppendLine("Ensure to call LoadPrivateKeyEx with password provider before calling Find(true)."); Utils.LogWarning(message.ToString(), StoreType); } m_certificate = certificate; } } } // use the single instance in the certificate cache. if (needPrivateKey) { certificate = m_certificate = CertificateFactory.Load(certificate, true); } return(certificate); }
/// <summary> /// Adds an application certificate to a store. /// </summary> private static void AddApplicationCertificateToStore( CertificateStoreIdentifier csid, X509Certificate2 certificate, string oldThumbprint) { ICertificateStore store = csid.OpenStore(); try { // delete the old certificate. if (oldThumbprint != null) { store.Delete(oldThumbprint); } // delete certificates with the same application uri. if (store.FindByThumbprint(certificate.Thumbprint) != null) { return; } string applicationUri = Utils.GetApplicationUriFromCertficate(certificate); // delete any existing certificates. foreach (X509Certificate2 target in store.Enumerate()) { if (!Utils.CompareDistinguishedName(target.Subject, certificate.Subject)) { continue; } if (Utils.GetApplicationUriFromCertficate(target) == applicationUri) { store.Delete(target.Thumbprint); } } // add new certificate. store.Add(new X509Certificate2(certificate.RawData)); } finally { store.Close(); } }
public async Task <X509Certificate2Collection> GetCertificates() { X509Certificate2Collection collection = new X509Certificate2Collection(); CertificateStoreIdentifier id = new CertificateStoreIdentifier(); id.StoreType = this.StoreType; id.StorePath = this.StorePath; if (!String.IsNullOrEmpty(id.StorePath)) { try { ICertificateStore store = id.OpenStore(); try { collection = await store.Enumerate().ConfigureAwait(false); } finally { store.Close(); } } catch (Exception) { // TODO check all StorePath references to not leak information Utils.LogError("Could not load certificates from store: {0}.", this.StorePath); } } foreach (CertificateIdentifier trustedCertificate in TrustedCertificates) { X509Certificate2 certificate = await trustedCertificate.Find().ConfigureAwait(false); if (certificate != null) { collection.Add(certificate); } } return(collection); }
/// <summary> /// Adds the certificate to the Trusted Certificate Store /// </summary> /// <param name="configuration">The application's configuration which specifies the location of the TrustedStore.</param> /// <param name="certificate">The certificate to register.</param> public static async Task AddToTrustedStore(ApplicationConfiguration configuration, X509Certificate2 certificate) { ICertificateStore store = configuration.SecurityConfiguration.TrustedPeerCertificates.OpenStore(); try { // check if it already exists. X509Certificate2Collection existingCertificates = await store.FindByThumbprint(certificate.Thumbprint); if (existingCertificates.Count > 0) { return; } List <string> subjectName = Utils.ParseDistinguishedName(certificate.Subject); // check for old certificate. X509Certificate2Collection certificates = await store.Enumerate(); for (int ii = 0; ii < certificates.Count; ii++) { if (Utils.CompareDistinguishedName(certificates[ii], subjectName)) { if (certificates[ii].Thumbprint == certificate.Thumbprint) { return; } await store.Delete(certificates[ii].Thumbprint); break; } } // add new certificate. X509Certificate2 publicKey = new X509Certificate2(certificate.RawData); await store.Add(publicKey); } finally { store.Close(); } }
public X509Certificate2Collection GetCertificates() { X509Certificate2Collection collection = new X509Certificate2Collection(); CertificateStoreIdentifier id = new CertificateStoreIdentifier(); id.StoreType = this.StoreType; id.StorePath = this.StorePath; if (!String.IsNullOrEmpty(id.StorePath)) { try { ICertificateStore store = id.OpenStore(); try { collection = store.Enumerate(); } finally { store.Close(); } } catch (Exception) { Utils.Trace("Could not load certificates from store: {0}.", this.StorePath); } } foreach (CertificateIdentifier trustedCertificate in TrustedCertificates) { X509Certificate2 certificate = trustedCertificate.Find(); if (certificate != null) { collection.Add(certificate); } } return(collection); }
private async Task <bool> UpdateStoreCertificates( CertificateTrustList trustList, X509Certificate2Collection updatedCerts) { bool result = true; ICertificateStore store = null; try { store = trustList.OpenStore(); var storeCerts = await store.Enumerate().ConfigureAwait(false); foreach (var cert in storeCerts) { if (!updatedCerts.Contains(cert)) { if (!store.Delete(cert.Thumbprint).Result) { result = false; } } else { updatedCerts.Remove(cert); } } foreach (var cert in updatedCerts) { await store.Add(cert).ConfigureAwait(false); } } catch { result = false; } finally { store?.Close(); } return(result); }
public virtual async Task Init() { string subjectName = Configuration.SubjectName.Replace("localhost", Utils.GetHostName()); Utils.Trace(Utils.TraceMasks.Information, "InitializeCertificateGroup: {0}", subjectName); using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(m_authoritiesStorePath)) { X509Certificate2Collection certificates = await store.Enumerate(); foreach (var certificate in certificates) { if (Utils.CompareDistinguishedName(certificate.Subject, subjectName)) { if (Certificate != null) { // always use latest issued cert in store if (Certificate.NotBefore > certificate.NotBefore) { continue; } } Certificate = certificate; } } } if (Certificate == null) { Utils.Trace(Utils.TraceMasks.Security, "Create new CA Certificate: {0}, KeySize: {1}, HashSize: {2}, LifeTime: {3} months", subjectName, Configuration.DefaultCertificateKeySize, Configuration.DefaultCertificateHashSize, Configuration.DefaultCertificateLifetime ); X509Certificate2 newCertificate = await CreateCACertificateAsync(subjectName); Certificate = new X509Certificate2(newCertificate.RawData); } }
/// <summary> /// Updates the certificate authority certificate and CRL in the trusted list. /// </summary> protected async Task UpdateAuthorityCertInTrustedList() { string trustedListStorePath = Configuration.TrustedListPath; if (!String.IsNullOrEmpty(Configuration.TrustedListPath)) { using (ICertificateStore authorityStore = CertificateStoreIdentifier.OpenStore(m_authoritiesStorePath)) using (ICertificateStore trustedStore = CertificateStoreIdentifier.OpenStore(trustedListStorePath)) { X509Certificate2Collection certificates = await authorityStore.Enumerate(); foreach (var certificate in certificates) { if (Utils.CompareDistinguishedName(certificate.Subject, m_subjectName)) { X509Certificate2Collection certs = await trustedStore.FindByThumbprint(certificate.Thumbprint); if (certs.Count == 0) { await trustedStore.Add(new X509Certificate2(certificate.RawData)); } // delete existing CRL in trusted list foreach (var crl in trustedStore.EnumerateCRLs(certificate, false)) { if (crl.VerifySignature(certificate, false)) { trustedStore.DeleteCRL(crl); } } // copy latest CRL to trusted list foreach (var crl in authorityStore.EnumerateCRLs(certificate, true)) { trustedStore.AddCRL(crl); } } } } } }
private ServiceResult GetRejectedList( ISystemContext context, MethodState method, NodeId objectId, ref byte[][] certificates) { HasApplicationSecureAdminAccess(context); using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(m_rejectedStorePath)) { X509Certificate2Collection collection = store.Enumerate().Result; List <byte[]> rawList = new List <byte[]>(); foreach (var cert in collection) { rawList.Add(cert.RawData); } certificates = rawList.ToArray(); } return(StatusCodes.Good); }
private async Task <bool> UpdateStoreCertificates( string storePath, X509Certificate2Collection updatedCerts) { bool result = true; try { using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(storePath)) { var storeCerts = await store.Enumerate().ConfigureAwait(false); foreach (var cert in storeCerts) { if (!updatedCerts.Contains(cert)) { if (!await store.Delete(cert.Thumbprint).ConfigureAwait(false)) { result = false; } } else { updatedCerts.Remove(cert); } } foreach (var cert in updatedCerts) { await store.Add(cert).ConfigureAwait(false); } } } catch { result = false; } return(result); }
private bool UpdateStoreCertificates( string storePath, X509Certificate2Collection updatedCerts) { bool result = true; try { using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(storePath)) { var storeCerts = store.Enumerate().Result; foreach (var cert in storeCerts) { if (!updatedCerts.Contains(cert)) { if (!store.Delete(cert.Thumbprint).Result) { result = false; } } else { updatedCerts.Remove(cert); } } foreach (var cert in updatedCerts) { store.Add(cert).Wait(); } } } catch { result = false; } return(result); }
/// <summary> /// Returns the certificate information for a trusted issuer certificate. /// </summary> private async Task <CertificateIdentifier> GetIssuer( X509Certificate2 certificate, CertificateIdentifierCollection explicitList, CertificateStoreIdentifier certificateStore, bool checkRecovationStatus) { string subjectName = certificate.IssuerName.Name; string keyId = null; string serialNumber = null; // find the authority key identifier. X509AuthorityKeyIdentifierExtension authority = FindAuthorityKeyIdentifier(certificate); if (authority != null) { keyId = authority.KeyId; serialNumber = authority.SerialNumber; } // check in explicit list. if (explicitList != null) { for (int ii = 0; ii < explicitList.Count; ii++) { X509Certificate2 issuer = await explicitList[ii].Find(false); if (issuer != null) { if (!IsIssuerAllowed(issuer)) { continue; } if (Match(issuer, subjectName, serialNumber, keyId)) { // can't check revocation. return(new CertificateIdentifier(issuer, CertificateValidationOptions.SuppressRevocationStatusUnknown)); } } } } // check in certificate store. if (certificateStore != null) { ICertificateStore store = certificateStore.OpenStore(); try { X509Certificate2Collection certificates = await store.Enumerate(); for (int ii = 0; ii < certificates.Count; ii++) { X509Certificate2 issuer = certificates[ii]; if (issuer != null) { if (!IsIssuerAllowed(issuer)) { continue; } if (Match(issuer, subjectName, serialNumber, keyId)) { CertificateValidationOptions options = certificateStore.ValidationOptions; // already checked revocation for file based stores. windows based stores always suppress. options |= CertificateValidationOptions.SuppressRevocationStatusUnknown; if (checkRecovationStatus) { StatusCode status = store.IsRevoked(issuer, certificate); if (StatusCode.IsBad(status)) { if (status != StatusCodes.BadNotSupported && status != StatusCodes.BadCertificateRevocationUnknown) { throw new ServiceResultException(status); } } } return(new CertificateIdentifier(certificates[ii], options)); } } } } finally { store.Close(); } } // not a trusted issuer. return(null); }
public override async Task Init() { Utils.Trace(Utils.TraceMasks.Information, "InitializeCertificateGroup: {0}", m_subjectName); X509Certificate2Collection rootCACertificateChain; IList <Opc.Ua.X509CRL> rootCACrlChain; try { // read root CA chain for certificate group rootCACertificateChain = await _opcVaultHandler.GetCACertificateChainAsync(Configuration.Id).ConfigureAwait(false); rootCACrlChain = await _opcVaultHandler.GetCACrlChainAsync(Configuration.Id).ConfigureAwait(false); var rootCaCert = rootCACertificateChain[0]; var rootCaCrl = rootCACrlChain[0]; if (Utils.CompareDistinguishedName(rootCaCert.Subject, m_subjectName)) { Certificate = rootCaCert; rootCaCrl.VerifySignature(rootCaCert, true); } else { throw new ServiceResultException("Key Vault certificate subject(" + rootCaCert.Subject + ") does not match cert group subject " + m_subjectName); } } catch (Exception ex) { Utils.Trace("Failed to load CA certificate " + Configuration.Id + " from key Vault "); Utils.Trace(ex.Message); throw ex; } // add all existing cert versions to trust list // erase old certs using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(m_authoritiesStorePath)) { try { X509Certificate2Collection certificates = await store.Enumerate(); foreach (var certificate in certificates) { // TODO: Subject may have changed over time if (Utils.CompareDistinguishedName(certificate.Subject, m_subjectName)) { var certs = rootCACertificateChain.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, false); if (certs == null || certs.Count == 0) { Utils.Trace("Delete CA certificate from authority store: " + certificate.Thumbprint); // delete existing CRL in trusted list foreach (var crl in store.EnumerateCRLs(certificate, false)) { if (crl.VerifySignature(certificate, false)) { store.DeleteCRL(crl); } } await store.Delete(certificate.Thumbprint); } } } } catch (Exception ex) { Utils.Trace("Failed to Delete existing certificates from authority store: " + ex.Message); } foreach (var rootCACertificate in rootCACertificateChain) { X509Certificate2Collection certs = await store.FindByThumbprint(rootCACertificate.Thumbprint); if (certs.Count == 0) { await store.Add(rootCACertificate); Utils.Trace("Added CA certificate to authority store: " + rootCACertificate.Thumbprint); } else { Utils.Trace("CA certificate already exists in authority store: " + rootCACertificate.Thumbprint); } foreach (var rootCACrl in rootCACrlChain) { if (rootCACrl.VerifySignature(rootCACertificate, false)) { // delete existing CRL in trusted list foreach (var crl in store.EnumerateCRLs(rootCACertificate, false)) { if (crl.VerifySignature(rootCACertificate, false)) { store.DeleteCRL(crl); } } store.AddCRL(rootCACrl); } } } // load trust list from server var trustList = await _opcVaultHandler.GetTrustListAsync(Configuration.Id).ConfigureAwait(false); await UpdateTrustList(trustList); } }
private ServiceResult Open( ISystemContext context, MethodState method, NodeId objectId, OpenFileMode mode, TrustListMasks masks, ref uint fileHandle) { HasSecureReadAccess(context); if (mode == OpenFileMode.Read) { HasSecureReadAccess(context); } else if (mode == (OpenFileMode.Write | OpenFileMode.EraseExisting)) { HasSecureWriteAccess(context); } else { return(StatusCodes.BadNotWritable); } lock (m_lock) { if (m_sessionId != null) { // to avoid deadlocks, last open always wins m_sessionId = null; m_strm = null; m_node.OpenCount.Value = 0; } m_readMode = mode == OpenFileMode.Read; m_sessionId = context.SessionId; fileHandle = ++m_fileHandle; TrustListDataType trustList = new TrustListDataType() { SpecifiedLists = (uint)masks }; using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(m_trustedStorePath)) { if ((masks & TrustListMasks.TrustedCertificates) != 0) { X509Certificate2Collection certificates = store.Enumerate().Result; foreach (var certificate in certificates) { trustList.TrustedCertificates.Add(certificate.RawData); } } if ((masks & TrustListMasks.TrustedCrls) != 0) { foreach (var crl in store.EnumerateCRLs()) { trustList.TrustedCrls.Add(crl.RawData); } } } using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(m_issuerStorePath)) { if ((masks & TrustListMasks.IssuerCertificates) != 0) { X509Certificate2Collection certificates = store.Enumerate().Result; foreach (var certificate in certificates) { trustList.IssuerCertificates.Add(certificate.RawData); } } if ((masks & TrustListMasks.IssuerCrls) != 0) { foreach (var crl in store.EnumerateCRLs()) { trustList.IssuerCrls.Add(crl.RawData); } } } if (m_readMode) { m_strm = EncodeTrustListData(context, trustList); } else { m_strm = new MemoryStream(DefaultTrustListCapacity); } m_node.OpenCount.Value = 1; } return(ServiceResult.Good); }
/// <summary> /// Adds the certificate to the Trusted Certificate Store /// </summary> /// <param name="configuration">The application's configuration which specifies the location of the TrustedStore.</param> /// <param name="certificate">The certificate to register.</param> private static void AddToTrustedStore(ApplicationConfiguration configuration, X509Certificate2 certificate) { var storePath = configuration?.SecurityConfiguration?.TrustedPeerCertificates?.StorePath; if (string.IsNullOrEmpty(storePath)) { Utils.Trace(Utils.TraceMasks.Information, "WARNING: Trusted peer store not specified."); return; } try { ICertificateStore store = configuration.SecurityConfiguration.TrustedPeerCertificates.OpenStore(); if (store == null) { Utils.Trace("Could not open trusted peer store. StorePath={0}", storePath); return; } try { // check if it is already stored X509Certificate2 certificate2 = store.FindByThumbprint(certificate.Thumbprint); if (certificate2 != null) { return; } Utils.Trace(Utils.TraceMasks.Information, "Adding certificate to trusted peer store. StorePath={0}", storePath); List <string> subjectName = Utils.ParseDistinguishedName(certificate.Subject); // check for old certificate. X509Certificate2Collection certificates = store.Enumerate(); foreach (var cert in certificates) { if (!Utils.CompareDistinguishedName(cert, subjectName)) { continue; } if (cert.Thumbprint == certificate.Thumbprint) { return; } store.Delete(cert.Thumbprint); break; } // add new certificate. X509Certificate2 publicKey = new X509Certificate2(certificate.GetRawCertData()); store.Add(publicKey); } finally { store.Close(); } } catch (Exception e) { Utils.Trace(e, "Could not add certificate to trusted peer store. StorePath={0}", storePath); } }
/// <summary> /// Show all certificates in the certificate stores. /// </summary> private static async Task ShowCertificateStoreInformationAsync( ApplicationConfiguration appConfig, ILogger logger) { // show application certs try { using ICertificateStore certStore = appConfig.SecurityConfiguration.ApplicationCertificate.OpenStore(); var certs = await certStore.Enumerate().ConfigureAwait(false); int certNum = 1; logger.Information("Application own certificate store contains {count} certs.", certs.Count); foreach (var cert in certs) { logger.Information("{certNum:D2}: Subject '{subject}' (thumbprint: {thumbprint})", certNum++, cert.Subject, cert.Thumbprint); } } catch (Exception e) { logger.Error(e, "Error while trying to read information from application store."); } // show trusted issuer certs try { using ICertificateStore certStore = appConfig.SecurityConfiguration.TrustedIssuerCertificates.OpenStore(); var certs = await certStore.Enumerate().ConfigureAwait(false); int certNum = 1; logger.Information("Trusted issuer store contains {count} certs.", certs.Count); foreach (var cert in certs) { logger.Information("{certNum:D2}: Subject '{subject}' (thumbprint: {thumbprint})", certNum++, cert.Subject, cert.Thumbprint); } if (certStore.SupportsCRLs) { var crls = await certStore.EnumerateCRLs().ConfigureAwait(false); int crlNum = 1; logger.Information("Trusted issuer store has {count} CRLs.", crls.Count); foreach (var crl in crls) { logger.Information("{crlNum:D2}: Issuer '{issuer}', Next update time '{nextUpdate}'", crlNum++, crl.Issuer, crl.NextUpdate); } } } catch (Exception e) { logger.Error(e, "Error while trying to read information from trusted issuer store."); } // show trusted peer certs try { using ICertificateStore certStore = appConfig.SecurityConfiguration.TrustedPeerCertificates.OpenStore(); var certs = await certStore.Enumerate().ConfigureAwait(false); int certNum = 1; logger.Information("Trusted peer store contains {count} certs.", certs.Count); foreach (var cert in certs) { logger.Information("{certNum:D2}: Subject '{subject}' (thumbprint: {thumbprint})", certNum++, cert.Subject, cert.Thumbprint); } if (certStore.SupportsCRLs) { var crls = await certStore.EnumerateCRLs().ConfigureAwait(false); int crlNum = 1; logger.Information("Trusted peer store has {count} CRLs.", crls.Count); foreach (var crl in crls) { logger.Information("{crlNum:D2}: Issuer '{issuer}', Next update time '{nextUpdate}'", crlNum++, crl.Issuer, crl.NextUpdate); } } } catch (Exception e) { logger.Error(e, "Error while trying to read information from trusted peer store."); } // show rejected peer certs try { using ICertificateStore certStore = appConfig.SecurityConfiguration.RejectedCertificateStore.OpenStore(); var certs = await certStore.Enumerate().ConfigureAwait(false); int certNum = 1; logger.Information("Rejected certificate store contains {count} certs.", certs.Count); foreach (var cert in certs) { logger.Information("{certNum:D2}: Subject '{subject}' (thumbprint: {thumbprint})", certNum++, cert.Subject, cert.Thumbprint); } } catch (Exception e) { logger.Error(e, "Error while trying to read information from rejected certificate store."); } }
/// <summary> /// Adds the certificate to the Trusted Certificate Store /// </summary> /// <param name="configuration">The application's configuration which specifies the location of the TrustedStore.</param> /// <param name="certificate">The certificate to register.</param> private static async Task AddToTrustedStore(ApplicationConfiguration configuration, X509Certificate2 certificate) { if (certificate == null) { throw new ArgumentNullException(nameof(certificate)); } string storePath = null; if (configuration != null && configuration.SecurityConfiguration != null && configuration.SecurityConfiguration.TrustedPeerCertificates != null) { storePath = configuration.SecurityConfiguration.TrustedPeerCertificates.StorePath; } if (String.IsNullOrEmpty(storePath)) { Utils.Trace(Utils.TraceMasks.Information, "WARNING: Trusted peer store not specified."); return; } try { ICertificateStore store = configuration.SecurityConfiguration.TrustedPeerCertificates.OpenStore(); if (store == null) { Utils.Trace("Could not open trusted peer store. StorePath={0}", storePath); return; } try { // check if it already exists. X509Certificate2Collection existingCertificates = await store.FindByThumbprint(certificate.Thumbprint); if (existingCertificates.Count > 0) { return; } Utils.Trace(Utils.TraceMasks.Information, "Adding certificate to trusted peer store. StorePath={0}", storePath); List <string> subjectName = X509Utils.ParseDistinguishedName(certificate.Subject); // check for old certificate. X509Certificate2Collection certificates = await store.Enumerate(); for (int ii = 0; ii < certificates.Count; ii++) { if (X509Utils.CompareDistinguishedName(certificates[ii], subjectName)) { if (certificates[ii].Thumbprint == certificate.Thumbprint) { return; } await store.Delete(certificates[ii].Thumbprint); break; } } // add new certificate. X509Certificate2 publicKey = new X509Certificate2(certificate.RawData); await store.Add(publicKey); } finally { store.Close(); } } catch (Exception e) { Utils.Trace(e, "Could not add certificate to trusted peer store. StorePath={0}", storePath); } }
public async void Initialize(string trustedStorePath, string issuerStorePath, string rejectedStorePath) { CertificatesTable.Rows.Clear(); m_trustedStorePath = trustedStorePath; m_issuerStorePath = issuerStorePath; m_rejectedStorePath = rejectedStorePath; if (!String.IsNullOrEmpty(trustedStorePath)) { using (ICertificateStore store = CreateStore(trustedStorePath)) { X509CertificateCollection certificates = await store.Enumerate(); foreach (X509Certificate2 certificate in certificates) { List <X509CRL> crls = new List <X509CRL>(); if (store.SupportsCRLs) { foreach (X509CRL crl in store.EnumerateCRLs(certificate)) { crls.Add(crl); } } AddCertificate(certificate, Status.Trusted, crls); } } } string path1 = Utils.GetAbsoluteDirectoryPath(trustedStorePath, true, false, false); string path2 = Utils.GetAbsoluteDirectoryPath(issuerStorePath, true, false, false); if (String.Compare(path1, path2, StringComparison.OrdinalIgnoreCase) != 0) { if (!String.IsNullOrEmpty(issuerStorePath)) { using (ICertificateStore store = CreateStore(issuerStorePath)) { X509Certificate2Collection certificates = await store.Enumerate(); foreach (X509Certificate2 certificate in certificates) { List <X509CRL> crls = new List <X509CRL>(); if (store.SupportsCRLs) { foreach (X509CRL crl in store.EnumerateCRLs(certificate)) { crls.Add(crl); } } AddCertificate(certificate, Status.Issuer, crls); } } } } if (!String.IsNullOrEmpty(rejectedStorePath)) { using (ICertificateStore store = CreateStore(rejectedStorePath)) { X509Certificate2Collection certificates = await store.Enumerate(); foreach (X509Certificate2 certificate in certificates) { AddCertificate(certificate, Status.Rejected, null); } } } m_dataset.AcceptChanges(); NoDataWarningLabel.Visible = CertificatesTable.Rows.Count == 0; }