Beispiel #1
0
        public static X509Certificate2 GetCertificate(
            string CertificateSubject,
            StoreName store        = StoreName.Root,
            StoreLocation location = StoreLocation.CurrentUser)
        {
            var x509Store = new X509Store(store, location);

            x509Store.Open(OpenFlags.ReadOnly);
            var certSubj = $"CN={CertificateSubject}";

            X509Certificate2Collection col = x509Store.Certificates;

            foreach (var certificate in col)
            {
                if (certificate.Subject.StartsWith(certSubj))
                {
                    _logger.Info($"find the '{CertificateSubject}' certificate");
                    x509Store.Dispose();

                    return(certificate);
                }
            }
            x509Store.Dispose();
            throw new CertificateException($"can't find a certificate by the '{certSubj}' subject");
        }
Beispiel #2
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _store?.Dispose();
     }
 }
Beispiel #3
0
        public X509SecurityTokenProvider(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue)
        {
            if (findValue == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue");
            }

            X509Store store = new X509Store(storeName, storeLocation);
            X509Certificate2Collection certificates = null;

            try
            {
                store.Open(OpenFlags.ReadOnly);
                certificates = store.Certificates.Find(findType, findValue, false);
                if (certificates.Count < 1)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(string.Format(SRServiceModel.CannotFindCert, storeName, storeLocation, findType, findValue)));
                }
                if (certificates.Count > 1)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(string.Format(SRServiceModel.FoundMultipleCerts, storeName, storeLocation, findType, findValue)));
                }

                _certificate = new X509Certificate2(certificates[0].Handle);
            }
            finally
            {
                System.ServiceModel.Security.SecurityUtils.ResetAllCertificates(certificates);
                store.Dispose();
            }
        }
Beispiel #4
0
        private X509Certificate2 FindCertificate(IDictionary <string, string> challengeData)
        {
            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            try
            {
                store.Open(OpenFlags.ReadOnly);
                var certCollection = store.Certificates;
                if (challengeData.ContainsKey("CertAuthorities"))
                {
                    return(FindCertificateByCertAuthorities(challengeData, certCollection));
                }

                X509Certificate2Collection signingCert = null;
                signingCert = certCollection.Find(X509FindType.FindByThumbprint, challengeData["CertThumbprint"],
                                                  false);
                if (signingCert.Count == 0)
                {
                    throw new MsalException(MsalError.DeviceCertificateNotFound,
                                            string.Format(CultureInfo.CurrentCulture, MsalErrorMessage.DeviceCertificateNotFoundTemplate,
                                                          "Cert thumbprint:" + challengeData["CertThumbprint"]));
                }

                return(signingCert[0]);
            }
            finally
            {
#if NETSTANDARD || WINDOWS_APP
                store.Dispose();
#else
                store.Close();
#endif
            }
        }
Beispiel #5
0
        /// <summary>
        /// ensures given certificate is installed, and returns the thumbprint
        /// </summary>
        /// <param name="file">x509Certificate2 file</param>
        /// <param name="password">password for the certificate</param>
        /// <returns>thumbprint</returns>
        public static string EnsureCertificateInstalled(string file, string password)
        {
            if (!File.Exists(file))
            {
                throw new FileNotFoundException("Could not find cert file");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("password must be provided", nameof(password));
            }

            var cert = new X509Certificate2(file, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            if (cert.Thumbprint == null)
            {
                throw new ApplicationException("Could not get thumbprint from cert");
            }

            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadWrite);
            var storeResults = store.Certificates.Find(X509FindType.FindByThumbprint, cert.Thumbprint, false);

            //install cert
            if (storeResults.Count == 0)
            {
                store.Add(cert);
            }
            store.Close();
            store.Dispose();

            return(cert.Thumbprint);
        }
Beispiel #6
0
        private static X509Certificate2 GetCertificateFromStoreCore(StoreName storeName, StoreLocation storeLocation,
                                                                    X509FindType findType, object findValue, EndpointAddress target, bool throwIfMultipleOrNoMatch)
        {
            if (findValue == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue");
            }

            X509Store store = new X509Store(storeName, storeLocation);
            X509Certificate2Collection certs = null;

            try
            {
                store.Open(OpenFlags.ReadOnly);
                certs = store.Certificates.Find(findType, findValue, false);
                if (certs.Count == 1)
                {
                    return(new X509Certificate2(certs[0]));
                }
                if (throwIfMultipleOrNoMatch)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateCertificateLoadException(
                                                                                  storeName, storeLocation, findType, findValue, target, certs.Count));
                }
                else
                {
                    return(null);
                }
            }
            finally
            {
                ResetAllCertificates(certs);
                store.Dispose();
            }
        }
Beispiel #7
0
        internal static X509Certificate2Collection GetRemoteCertificatesFromStoreContext(SafeFreeCertContext certContext)
        {
            X509Certificate2Collection result = new X509Certificate2Collection();

            if (certContext.IsInvalid)
            {
                return(result);
            }

            Interop.Crypt32.CERT_CONTEXT context = Marshal.PtrToStructure <Interop.Crypt32.CERT_CONTEXT>(certContext.DangerousGetHandle());

            if (context.hCertStore != IntPtr.Zero)
            {
                X509Store store = null;
                try
                {
                    store  = X509StoreExtensions.CreateFromNativeHandle(context.hCertStore);
                    result = store.Certificates;
                }
                finally
                {
                    if (store != null)
                    {
                        store.Dispose();
                    }
                }
            }
            return(result);
        }
        /// <summary>
        /// Finds the cert having thumbprint supplied from store location supplied
        /// </summary>
        /// <param name="storeName"></param>
        /// <param name="storeLocation"></param>
        /// <param name="thumbprint"></param>
        /// <param name="validationRequired"></param>
        /// <returns>X509Certificate2</returns>
        public static X509Certificate2 FindCertificateByThumbprint(StoreName storeName, StoreLocation storeLocation, string thumbprint, bool validationRequired)
        {
            var store = new X509Store(storeName, storeLocation);

            try
            {
                store.Open(OpenFlags.ReadOnly);
                var col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validationRequired);
                if (col == null || col.Count == 0)
                {
                    throw new ArgumentException($"Certificate was not found in store {storeName}:{storeLocation}");
                }

                return(col[0]);
            }
            finally
            {
#if NET451
                // IDisposable not implemented in NET451
                store.Close();
#else
                // Close is private in DNXCORE, but Dispose calls close internally
                store.Dispose();
#endif
            }
        }
Beispiel #9
0
        public void RemoteCertificateValidationRulesTest()
        {
            //ARRANGE
            var configuration = new CertificateValidationConfiguration
            {
                UsePinningValidation          = false,
                X509CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.Custom
            };
            var configurationProvider = new CertificateValidationConfigurationProvider(() => configuration);
            var validator             = new BackchannelCertificateValidator(configurationProvider);

            var certificateStore = new X509Store("TestCertStore", StoreLocation.LocalMachine);
            var validationResult = false;

            //ACT
            try
            {
                certificateStore.Open(OpenFlags.ReadOnly);
                var certificate = certificateStore.Certificates.Find(X509FindType.FindBySubjectName, "ApiraTestCertificate", false)[0];
                var x509Chain   = new X509Chain(true);
                x509Chain.Build(certificate);
                validationResult = validator.Validate(this, certificate, x509Chain, SslPolicyErrors.None);
            }
            finally
            {
                certificateStore.Close();
                certificateStore.Dispose();
            }
            //ASSERT
            Assert.True(validationResult);
        }
Beispiel #10
0
        public static List enum_crls(string store_name)
        {
            X509Store store = null;

            try {
                store = new X509Store(store_name, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);
                var result = new List();

                foreach (var cert in store.Certificates)
                {
                    string format = cert.GetFormat();
                }
            } catch {
            } finally {
                if (store != null)
                {
#if NETSTANDARD
                    store.Dispose();
#else
                    store.Close();
#endif
                }
            }
            return(new List());
        }
Beispiel #11
0
        /// <summary>
        /// Used for Proxy
        /// </summary>
        public static X509Certificate2 LoadCertificate(string thumbprintOrSubjectName)
        {
            var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            try
            {
                // Certificate must be in the local machine store
                certStore.Open(OpenFlags.ReadOnly);

                // Attempt to find by Thumbprint first
                var matchingCertificates = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprintOrSubjectName, false);
                if (matchingCertificates.Count == 0)
                {
                    // Fallback to SubjectName
                    matchingCertificates = certStore.Certificates.Find(X509FindType.FindBySubjectName, thumbprintOrSubjectName, false);
                    if (matchingCertificates.Count == 0)
                    {
                        // No certificates matched the search criteria.
                        throw new FileNotFoundException("No certificate found with specified Thumbprint or SubjectName.", thumbprintOrSubjectName);
                    }
                }

                // Use the first matching certificate.
                return(matchingCertificates[0]);
            }
            finally
            {
#if NETSTANDARD || NET46
                certStore.Dispose();
#else
                certStore.Close();
#endif
            }
        }
Beispiel #12
0
        static X509Certificate2 GetCertificate(string certFindValue)
        {
            StoreLocation[] locations = new StoreLocation[] { StoreLocation.LocalMachine, StoreLocation.CurrentUser };
            foreach (StoreLocation location in locations)
            {
                X509Store store = new X509Store(StoreName.My, location);
                store.Open(OpenFlags.OpenExistingOnly);

                X509Certificate2Collection collection = store.Certificates.Find(
                    X509FindType.FindBySubjectName,
                    certFindValue,
                    false);

                if (collection.Count == 0)
                {
                    collection = store.Certificates.Find(
                        X509FindType.FindByThumbprint,
                        certFindValue,
                        false);
                }

#if DOTNET
                store.Dispose();
#else
                store.Close();
#endif
                if (collection.Count > 0)
                {
                    return(collection[0]);
                }
            }

            throw new ArgumentException("No certificate can be found using the find value " + certFindValue);
        }
Beispiel #13
0
        private static X509Certificate2 GetCertificateFromStore(string certName)
        {
            // Get the certificate store for the current user.
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                // Place all certificates in an X509Certificate2Collection object.
                X509Certificate2Collection certCollection = store.Certificates;
                // If using a certificate with a trusted root you do not need to FindByTimeValid, instead:
                // currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, true);
                X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
                X509Certificate2Collection signingCert  = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false);
                if (signingCert.Count == 0)
                {
                    return(null);
                }
                // Return the first certificate in the collection, has the right name and is current.
                return(signingCert[0]);
            }
            finally
            {
                store.Dispose();
            }
        }
Beispiel #14
0
 private X509Certificate2 GetCertFromStore(StoreLocation loc)
 {
     try
     {
         X509Store store = new X509Store(StoreName.My, loc);
         store.Open(OpenFlags.ReadOnly);
         try
         {
             var storeCert = store.Certificates.Find(
                 X509FindType.FindByThumbprint,
                 Certificate.Thumbprint,
                 true
                 ).OfType <X509Certificate2>().FirstOrDefault();
             return(storeCert);
         }
         finally
         {
             #if Core
             store.Dispose();
             #endif
             store.Close();
         }
     }
     catch
     {
         return(null);
     }
 }
Beispiel #15
0
        /// <summary>
        /// Uses a specific <see cref="X509Certificate2"/> retrieved from the
        /// given X509 store to sign tokens issued by the OpenID Connect server.
        /// </summary>
        /// <param name="builder">The options used to configure the OpenID Connect server.</param>
        /// <param name="thumbprint">The thumbprint of the certificate used to identify it in the X509 store.</param>
        /// <param name="name">The name of the X509 store.</param>
        /// <param name="location">The location of the X509 store.</param>
        /// <returns>The options used to configure the OpenID Connect server.</returns>
        public static OpenIdConnectServerBuilder UseCertificate(
            [NotNull] this OpenIdConnectServerBuilder builder,
            [NotNull] string thumbprint, StoreName name, StoreLocation location)
        {
            var store = new X509Store(name, location);

            try {
                store.Open(OpenFlags.ReadOnly);

                var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false);

                var certificate = certificates.OfType <X509Certificate2>().SingleOrDefault();
                if (certificate == null)
                {
                    throw new InvalidOperationException("The certificate corresponding to the given thumbprint was not found.");
                }

                return(builder.UseCertificate(certificate));
            }

            finally {
#if DNXCORE50
                store.Dispose();
#else
                store.Close();
#endif
            }
        }
Beispiel #16
0
        /// <summary>
        /// Remove the Root Certificate trust
        /// </summary>
        /// <param name="storeLocation"></param>
        /// <returns></returns>
        private void RemoveTrustedRootCertificates(StoreLocation storeLocation)
        {
            if (RootCertificate == null)
            {
                exceptionFunc(
                    new Exception("Could not set root certificate"
                                  + " as system proxy since it is null or empty."));

                return;
            }

            var x509RootStore     = new X509Store(StoreName.Root, storeLocation);
            var x509PersonalStore = new X509Store(StoreName.My, storeLocation);

            try
            {
                x509RootStore.Open(OpenFlags.ReadWrite);
                x509PersonalStore.Open(OpenFlags.ReadWrite);

                x509RootStore.Remove(RootCertificate);
                x509PersonalStore.Remove(RootCertificate);
            }
            catch (Exception e)
            {
                exceptionFunc(
                    new Exception("Failed to remove root certificate trust "
                                  + $" for {storeLocation} store location. You may need admin rights.", e));
            }
            finally
            {
                x509RootStore.Dispose();
                x509PersonalStore.Dispose();
            }
        }
Beispiel #17
0
        private static X509Certificate2Collection EnumerateFromStore(StoreLocation location, string name)
        {
            X509Store store = null;
            X509Certificate2Collection result = new X509Certificate2Collection();

            try
            {
#if NET46
                using store = new X509Store(name, location);
#else
                store = new X509Store(name, location);
#endif
                store.Open(OpenFlags.ReadOnly | OpenFlags.ReadOnly);
                foreach (var cert in store.Certificates)
                {
                    result.Add(new X509Certificate2(cert));
                }
            }
            finally
            {
#if NET46
                store?.Dispose();
#else
                store?.Close();
#endif
            }

            return(result);
        }
        internal X509Certificate2 GetApplicationCertificateFromStore()
        {
            HealthVaultPlatformTrace.LogCertLoading(
                "Opening cert store (read-only): {0}",
                _storeLocation.ToString());

            RSACng rsaProvider = null;
            string thumbprint  = null;

            X509Certificate2 result = null;
            X509Store        store  = new X509Store(_storeLocation);

            store.Open(OpenFlags.ReadOnly);

            try
            {
                HealthVaultPlatformTrace.LogCertLoading(
                    "Looking for matching cert with subject: {0}",
                    _certSubject);

                foreach (X509Certificate2 cert in store.Certificates)
                {
                    if (string.Equals(
                            cert.Subject,
                            _certSubject,
                            StringComparison.OrdinalIgnoreCase))
                    {
                        HealthVaultPlatformTrace.LogCertLoading(
                            "Found matching cert subject with thumbprint: {0}",
                            cert.Thumbprint);

                        thumbprint = cert.Thumbprint;

                        HealthVaultPlatformTrace.LogCertLoading("Looking for private key");
                        rsaProvider = (RSACng)cert.GetRSAPrivateKey();
                        HealthVaultPlatformTrace.LogCertLoading("Private key found");

                        result = cert;
                        break;
                    }
                }
            }
            catch (CryptographicException e)
            {
                HealthVaultPlatformTrace.LogCertLoading(
                    "Failed to retrieve private key for certificate: {0}",
                    e.ToString());
            }
            finally
            {
                store.Dispose();
            }

            if (rsaProvider == null || string.IsNullOrEmpty(thumbprint))
            {
                throw new SecurityException("CertificateNotFound");
            }

            return(result);
        }
        protected override void Dispose(bool disposing)
        {
            _listener?.DeleteAnonymousTLSIdentity();
            base.Dispose(disposing);

            _store.Dispose();
            _listener.Dispose();
        }
Beispiel #20
0
        public static void Dispose_IsOpenFalse()
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);
            store.Dispose();
            Assert.False(store.IsOpen);
        }
Beispiel #21
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
            TLSIdentity.DeleteIdentity(_store, ServerCertLabel, null);
            _store.Dispose();
        }
Beispiel #22
0
        public static List enum_certificates(string store_name)
        {
            X509Store store = null;

            try {
                store = new X509Store(store_name, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);
                var result = new List();

                foreach (var cert in store.Certificates)
                {
                    string format = cert.GetFormat();

                    switch (format)
                    {
                    case "X509":
                        format = "x509_asn";
                        break;

                    default:
                        format = "unknown";
                        break;
                    }

                    var  set   = new SetCollection();
                    bool found = false;
                    foreach (var ext in cert.Extensions)
                    {
                        var keyUsage = ext as X509EnhancedKeyUsageExtension;
                        if (keyUsage != null)
                        {
                            foreach (var oid in keyUsage.EnhancedKeyUsages)
                            {
                                set.add(oid.Value);
                            }
                            found = true;
                            break;
                        }
                    }

                    result.Add(PythonTuple.MakeTuple(new Bytes(cert.RawData.ToList()), format, found ? set : ScriptingRuntimeHelpers.True));
                }

                return(result);
            } catch {
            } finally {
                if (store != null)
                {
#if NETSTANDARD
                    store.Dispose();
#else
                    store.Close();
#endif
                }
            }
            return(new List());
        }
Beispiel #23
0
 void Dispose(bool disposing)
 {
     GC.SuppressFinalize(this);
     if (disposing)
     {
         _store.Dispose();
     }
     FreeHandle();
 }
Beispiel #24
0
        public void AddRootCaToStore(X509Certificate2 rootCert, StoreLocation storeLocation, StoreName storeName)
        {
            X509Store store = new X509Store(storeName, storeLocation);

            store.Open(OpenFlags.ReadWrite);
            store.Add(rootCert);

            store.Close();
            store.Dispose();
        }
Beispiel #25
0
        public X509Certificate2Collection GetCertificates()
        {
            X509Certificate2Collection certs = new X509Certificate2Collection();
            X509Store certificateStore       = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            try
            {
                certificateStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
                foreach (X509Certificate2 certificate in certificateStore.Certificates)
                {
                    if (certificate.HasPrivateKey)
                    {
                        bool digitalSignatureUsage     = false;
                        bool clientAuthEnhancedUsage   = false;
                        bool enhancedKeyUsageSupported = false;

                        foreach (X509Extension extension in certificate.Extensions)
                        {
                            X509KeyUsageExtension keyUsage = extension as X509KeyUsageExtension;
                            if (keyUsage != null)
                            {
                                digitalSignatureUsage = (keyUsage.KeyUsages & X509KeyUsageFlags.DigitalSignature) != 0;
                            }
                            else
                            {
                                X509EnhancedKeyUsageExtension enhancedKeyUsage = extension as X509EnhancedKeyUsageExtension;
                                if (enhancedKeyUsage != null && enhancedKeyUsage.EnhancedKeyUsages != null)
                                {
                                    enhancedKeyUsageSupported = true;
                                    foreach (var oid in enhancedKeyUsage.EnhancedKeyUsages)
                                    {
                                        if (oid.Value == OidClientAuthValue)
                                        {
                                            clientAuthEnhancedUsage = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        if (digitalSignatureUsage && (!enhancedKeyUsageSupported || clientAuthEnhancedUsage))
                        {
                            certs.Add(certificate);
                        }
                    }
                }
            }
            finally
            {
                certificateStore.Dispose();
            }

            return(certs);
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("Requires <Cert StoreName> <pfxfile> <friendlyname> and <password> arguments");
                return;
            }
            string certStoreName = args[0];
            string pfxFile       = args[1];
            string friendlyName  = args[2];
            string password      = args[3];

            X509Store store = new X509Store(certStoreName, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadWrite);


            var newCert = new X509Certificate2(pfxFile, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            newCert.FriendlyName = friendlyName;
            store.Add(newCert);


            if (File.Exists("previousHash.txt") && File.Exists("previousHash.bin"))
            {
                var oldHashText = File.ReadAllText("previousHash.txt").Trim();
                if (oldHashText == newCert.GetCertHashString())
                {
                    return;
                }
                var oldCert = store.Certificates.Find(X509FindType.FindByThumbprint, oldHashText, false);

                ServerManager mgr = new ServerManager();
                foreach (Site s in mgr.Sites)
                {
                    Console.WriteLine(s.Name);
                    foreach (var b in s.Bindings.Where(x => x.Protocol == "https" && x.CertificateHash.SequenceEqual(File.ReadAllBytes("previousHash.bin"))))
                    {
                        b.CertificateHash      = newCert.GetCertHash();
                        b.CertificateStoreName = certStoreName;
                        b.SetAttributeValue("certificateStoreName", certStoreName);
                        b.SetAttributeValue("certificateHash", newCert.GetCertHashString());
                    }
                }
                mgr.CommitChanges();
                store.RemoveRange(oldCert);
                store.Close();
                store.Dispose();
            }


            File.WriteAllBytes("previousHash.bin", newCert.GetCertHash());
            File.WriteAllText("previousHash.txt", newCert.GetCertHashString());
        }
Beispiel #27
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _store.Dispose();
                }
                disposedValue = true;
            }
        }
Beispiel #28
0
        //TODO cleanup. Perhaps a test or two.
        //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands"), SecuritySafeCritical]
        public X509Certificate2 GetCertByThumbprint(string thumbprint, StoreLocation storeLocation, StoreName storeName)
        {
            X509Store certStore = null;
            X509Certificate2Collection certs = null;

            try
            {
                certStore = new X509Store(storeName, storeLocation);
                certStore.Open(OpenFlags.ReadOnly);
                certs = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);

                if (certs.Count > 1)
                {
                    var message = string.Format("Something went horribly wrong, found more than one cert with thumbprint {0} in store location {1}, storename {2}", thumbprint, storeLocation, storeName);
                    throw new Exception(message);
                }

                if (certs.Count == 0)
                {
                    var message = string.Format("No certificate with thumbprint {0} in store location {1}, storename {2}", thumbprint, storeLocation, storeName);
                    throw new ArgumentException(message);
                }

                //Returns new cert, all existing certs will be cleaned up
                return(certs[0]);
            }
            catch
            {
                if (certs != null)
                {
                    foreach (var cert in certs)
                    {
                        CleanupCert(cert);
                    }
                }
                if (certStore != null)
                {
                    foreach (var cert in certStore.Certificates)
                    {
                        CleanupCert(cert);
                    }
#if DNX451
                    certStore.Close();
#elif NET451
                    certStore.Close();
#else
                    certStore.Dispose();
#endif
                }
                throw;
            }
        }
Beispiel #29
0
        /// <summary>
        /// Used by the WireMock.Net server
        /// </summary>
        public static X509Certificate2 LoadCertificate(
            string storeName,
            string storeLocation,
            string thumbprintOrSubjectName,
            string filePath,
            string password,
            string host)
        {
            if (!string.IsNullOrEmpty(storeName) && !string.IsNullOrEmpty(storeLocation))
            {
                var thumbprintOrSubjectNameOrHost = thumbprintOrSubjectName ?? host;

                var certStore = new X509Store((StoreName)Enum.Parse(typeof(StoreName), storeName), (StoreLocation)Enum.Parse(typeof(StoreLocation), storeLocation));
                try
                {
                    certStore.Open(OpenFlags.ReadOnly);

                    // Attempt to find by Thumbprint first
                    var matchingCertificates = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprintOrSubjectNameOrHost, false);
                    if (matchingCertificates.Count == 0)
                    {
                        // Fallback to SubjectName
                        matchingCertificates = certStore.Certificates.Find(X509FindType.FindBySubjectName, thumbprintOrSubjectNameOrHost, false);
                        if (matchingCertificates.Count == 0)
                        {
                            // No certificates matched the search criteria.
                            throw new FileNotFoundException($"No Certificate found with in store '{storeName}', location '{storeLocation}' for Thumbprint or SubjectName '{thumbprintOrSubjectNameOrHost}'.");
                        }
                    }

                    // Use the first matching certificate.
                    return(matchingCertificates[0]);
                }
                finally
                {
#if NETSTANDARD || NET46
                    certStore.Dispose();
#else
                    certStore.Close();
#endif
                }
            }

            if (!string.IsNullOrEmpty(filePath) && !string.IsNullOrEmpty(password))
            {
                return(new X509Certificate2(filePath, password));
            }

            throw new InvalidOperationException("X509StoreName and X509StoreLocation OR X509CertificateFilePath and X509CertificatePassword are mandatory.");
        }
Beispiel #30
0
        private X509Certificate2Collection FindCertificates(StoreName storeName, StoreLocation storeLocation, string findValue)
        {
            var x509Store = new X509Store(storeName, storeLocation);

            try
            {
                x509Store.Open(OpenFlags.OpenExistingOnly);
                return(x509Store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, findValue, false));
            }
            finally
            {
                x509Store.Dispose();
            }
        }