static void Main() { try { X509Store store = new X509Store("MY",StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = X509Certificate2UI.SelectFromCollection( (X509Certificate2Collection)store.Certificates, "Certificate selection", "Select a certificate to obtain the container name from", X509SelectionFlag.SingleSelection); if (collection.Count == 1) { X509Certificate2 x509 = collection[0] ; Console.WriteLine("Subject: {0}", x509.Subject) ; Console.WriteLine("Friendly name: {0}", x509.FriendlyName) ; if (x509.PrivateKey != null) { ICspAsymmetricAlgorithm pkey = x509.PrivateKey as ICspAsymmetricAlgorithm ; Console.WriteLine("Key container name: {0}", pkey.CspKeyContainerInfo.KeyContainerName); } x509.Reset(); } store.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()) ; } }
private static X509Certificate2 FindX509Certificate(string thumbprint) { List<StoreLocation> locations = new List<StoreLocation> { StoreLocation.CurrentUser, StoreLocation.LocalMachine }; foreach (var location in locations) { X509Store store = new X509Store("My", location); try { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection certificates = store.Certificates.Find( X509FindType.FindByThumbprint, thumbprint, false); if (certificates.Count == 1) { return certificates[0]; } } finally { store.Close(); } } throw new ArgumentException(string.Format("A Certificate with Thumbprint '{0}' could not be located.", thumbprint)); }
public static void X509CertStoreChain() { X509Store store = new X509Store("My", StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); // can't guarantee there is a certificate in store if (store.Certificates.Count > 0) { X509Chain chain = new X509Chain(); Assert.NotNull(chain.SafeHandle); Assert.Same(chain.SafeHandle, chain.SafeHandle); Assert.True(chain.SafeHandle.IsInvalid); foreach (X509Certificate2 c in store.Certificates) { // can't guarantee success, so no Assert if (chain.Build(c)) { foreach (X509ChainElement k in chain.ChainElements) { Assert.NotNull(k.Certificate.IssuerName.Name); } } } } }
public static X509Certificate2Collection GetCertificates(StoreName name, StoreLocation location) { X509Store store = null; try { store = new X509Store(name, location); X509Certificate2Collection certificates = null; store.Open(OpenFlags.ReadOnly); // Every time we call store.Certificates property, a new collection will be returned. return store.Certificates; } finally { if (store != null) { store.Close(); } } return null; }
X509Certificate2 LoadCertificate() { string thumbprint = ConfigurationManager.AppSettings["nuget:Thumbprint"]; Thumbprint = thumbprint; if (string.IsNullOrWhiteSpace(thumbprint)) { return null; } X509Store certStore = null; try { certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); certStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (certCollection.Count > 0) { return certCollection[0]; } return null; } finally { if (certStore != null) { certStore.Close(); } } }
public static void OpenNotExistant() { using (X509Store store = new X509Store(Guid.NewGuid().ToString("N"), StoreLocation.CurrentUser)) { Assert.ThrowsAny<CryptographicException>(() => store.Open(OpenFlags.OpenExistingOnly)); } }
public static void AddReadOnlyThrowsWhenCertificateExists() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); X509Certificate2 toAdd = null; // Look through the certificates to find one with no private key to call add on. // (The private key restriction is so that in the event of an "accidental success" // that no potential permissions would be modified) foreach (X509Certificate2 cert in store.Certificates) { if (!cert.HasPrivateKey) { toAdd = cert; break; } } if (toAdd != null) { Assert.ThrowsAny<CryptographicException>(() => store.Add(toAdd)); } } }
public static void OpenMyStore() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); } }
/// <summary> /// 获取微信现金红包信息接口 /// 是否需要证书:需要。 /// http://pay.weixin.qq.com/wiki/doc/api/cash_coupon.php?chapter=13_6 /// 使用说明 /// 用于商户对已发放的红包进行查询红包的具体信息,可支持普通红包和裂变包。 /// </summary> /// <param name="nonce_str">(必填) String(32) 随机字符串,不长于32位</param> /// <param name="mch_billno">(必填) String(28) 商户发放红包的商户订单号</param> /// <param name="mch_id">(必填) String(32) 微信支付分配的商户号</param> /// <param name="appid">(必填) String(32) 微信分配的公众账号ID</param> /// <param name="bill_type">(必填) String(32) 订单类型 例子:MCHT ,通过商户订单号获取红包信息。</param> /// <param name="partnerKey">API密钥</param> /// <param name="cert_path">秘钥路径</param> /// <param name="cert_password">秘钥密码</param> /// <returns>返回xml字符串,格式参见:http://pay.weixin.qq.com/wiki/doc/api/cash_coupon.php?chapter=13_6 </returns> public static string GetHbInfo(string nonce_str, string mch_billno, string mch_id, string appid, string bill_type, string partnerKey, string cert_path, string cert_password) { try { var stringADict = new Dictionary<string, string>(); stringADict.Add("nonce_str", nonce_str); stringADict.Add("mch_billno", mch_billno); stringADict.Add("mch_id", mch_id); stringADict.Add("appid", appid); stringADict.Add("bill_type", bill_type); var sign = WxPayAPI.Sign(stringADict, partnerKey);//生成签名字符串 var postdata = PayUtil.GeneralPostdata(stringADict, sign); var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo"; // 要注意的这是这个编码方式,还有内容的Xml内容的编码方式 Encoding encoding = Encoding.GetEncoding("UTF-8"); byte[] data = encoding.GetBytes(postdata); //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); //X509Certificate cer = new X509Certificate(cert_path, cert_password); ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); X509Certificate cer = new X509Certificate(cert_path, cert_password); #region 该部分是关键,若没有该部分则在IIS下会报 CA证书出错 X509Certificate2 certificate = new X509Certificate2(cert_path, cert_password); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Remove(certificate); //可省略 store.Add(certificate); store.Close(); #endregion HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url); webrequest.ClientCertificates.Add(cer); webrequest.Method = "post"; webrequest.ContentLength = data.Length; Stream outstream = webrequest.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Flush(); outstream.Close(); HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse(); Stream instream = webreponse.GetResponseStream(); string resp = string.Empty; using (StreamReader reader = new StreamReader(instream)) { resp = reader.ReadToEnd(); } return resp; } catch (Exception ex) { throw ex; } }
/// <summary> /// Gets the store certificate matching the thumbprint. The algorithm looks in both the current user and local machine stores and returns the first occurrence. /// </summary> /// <param name="thumbprint">The thumbprint.</param> /// <returns>Client certificate</returns> /// <exception cref="System.ArgumentException">A Certificate with Thumbprint '{0}' could not be located.</exception> private static X509Certificate2 GetStoreCertificate(string thumbprint) { var locations = new List<StoreLocation> { StoreLocation.CurrentUser, StoreLocation.LocalMachine }; foreach(var location in locations) { var store = new X509Store("My", location); try { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection certificates = store.Certificates.Find( X509FindType.FindByThumbprint, thumbprint, false); if(certificates.Count == 1) { return certificates[0]; } } finally { store.Close(); } } throw new ArgumentException(string.Format(Resources.Errors.CertificateNotFound, thumbprint)); }
public static void AddClosedThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { Assert.ThrowsAny<CryptographicException>(() => store.Add(cert)); } }
private static void Main(string[] args) { Task.Run(async () => { Console.WriteLine("Enter PIN: "); string pin = Console.ReadLine(); WebRequestHandler handler = new WebRequestHandler(); handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); using (HttpClient client = new HttpClient(handler, true)) { client.BaseAddress = new Uri(string.Format(@"https://{0}:{1}", MachineName, RemotePort)); X509Store store = null; try { var response = await client.GetAsync("certs/" + pin); response.EnsureSuccessStatusCode(); byte[] rawCert = await response.Content.ReadAsByteArrayAsync(); X509Certificate2Collection certs = new X509Certificate2Collection(); certs.Import(rawCert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.UserKeySet); store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection oldCerts = new X509Certificate2Collection(); foreach (var cert in certs) { oldCerts.AddRange(store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false)); } store.RemoveRange(certs); store.AddRange(certs); store.Close(); Console.WriteLine("Success"); } catch (HttpRequestException e) { Console.WriteLine("Error communicating with vcremote. Make sure that vcremote is running in secure mode and that a new client cert has been generated."); } finally { if (store != null) { store.Close(); } } } }).Wait(); }
public HttpClientExtensionsFixture() { var store = new X509Store(StoreName.TrustedPeople); store.Open(OpenFlags.ReadOnly); var certName = ConfigurationManager.AppSettings["AuthCertName"]; this.certificate = store.Certificates.Cast<X509Certificate2>() .Single(c => c.Subject.Equals(certName)); }
static void RemoveCertificatesFromStore(string cert , string password , StoreLocation loc) { //Import the pfx certificates X509Certificate2Collection certificates = new X509Certificate2Collection() ; certificates.Import( cert , password , X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); //Add the Certificate X509Store store = new X509Store( storeName , loc) ; // , "Cool Store" ) ; store.Open( OpenFlags.ReadWrite ) ; store.RemoveRange( certificates ) ; store.Close() ; }
public static X509Certificate2 GetEligibleClientCertificate() { // Get initial list of client certificates from the MY store. X509Certificate2Collection candidateCerts; using (var myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { myStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); candidateCerts = myStore.Certificates; } return GetEligibleClientCertificate(candidateCerts); }
public static void ReadMyCertificates() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); int certCount = store.Certificates.Count; // This assert is just so certCount appears to be used, the test really // is that store.get_Certificates didn't throw. Assert.True(certCount >= 0); } }
private static X509Certificate2 GetCertificate(string thumbprint) { X509Store store = new X509Store("My", StoreLocation.LocalMachine); store.Open(OpenFlags.OpenExistingOnly); foreach (X509Certificate2 cert in store.Certificates) { if (cert.Thumbprint == thumbprint) return cert; } return null; }
public static X509Certificate2 GetCertificate( StoreName name, StoreLocation location, string subjectName ) { X509Store store = new X509Store( name, location ); X509Certificate2Collection certificates = null; store.Open( OpenFlags.ReadOnly ); try { X509Certificate2 result = null; // // Every time we call store.Certificates property, a new collection will be returned. // certificates = store.Certificates; for ( int i = 0; i < certificates.Count; i++ ) { X509Certificate2 cert = certificates[i]; if ( cert.SubjectName.Name.ToLower() == subjectName.ToLower() ) { if ( result != null ) { throw new ApplicationException( string.Format( "There are multiple certificates for subject Name {0}", subjectName ) ); } result = new X509Certificate2( cert ); } } if ( result == null ) { throw new ApplicationException( string.Format( "No certificate was found for subject Name {0}", subjectName ) ); } return result; } finally { if ( certificates != null ) { for ( int i = 0; i < certificates.Count; i++ ) { X509Certificate2 cert = certificates[i]; cert.Reset(); } } store.Close(); } }
public JwtValidationHandlerFixture() { var store = new X509Store(StoreName.TrustedPeople); store.Open(OpenFlags.ReadOnly); var certName = ConfigurationManager.AppSettings["AuthCertName"]; this.certificate = store.Certificates.Cast<X509Certificate2>() .Single(c => c.Subject.Equals(certName)); this.rootRoute = string.Format( "{0}/entities", typeof(JwtValidationHandlerFixtureController).Name.ToLowerInvariant()); }
private static X509Certificate2 GetCertificate(string thumbprint) { X509Store store = new X509Store("My", StoreLocation.LocalMachine); store.Open(OpenFlags.OpenExistingOnly); foreach (X509Certificate2 cert in store.Certificates) { if (String.Equals(cert.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase)) { return cert; } } return null; }
static void Main(string[] args) { // // Create the authentication context to be used to acquire tokens. // authContext = new AuthenticationContext(authority); // // Initialize the Certificate Credential to be used by ADAL. // First find the matching certificate in the cert store. // X509Certificate2 cert = null; X509Store store = new X509Store(StoreLocation.CurrentUser); try { store.Open(OpenFlags.ReadOnly); // Place all certificates in an X509Certificate2Collection object. X509Certificate2Collection certCollection = store.Certificates; // Find unexpired certificates. X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false); // From the collection of unexpired certificates, find the ones with the correct name. X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false); if (signingCert.Count == 0) { // No matching certificate found. return; } // Return the first certificate in the collection, has the right name and is current. cert = signingCert[0]; } finally { store.Close(); } // Then create the certificate credential. certCred = new ClientAssertionCertificate(clientId, cert); // // Call the To Do service 10 times with short delay between calls. // for (int i = 0; i < 10; i++) { Thread.Sleep(3000); PostTodo().Wait(); Thread.Sleep(3000); GetTodo().Wait(); } }
public static void AddReadOnlyThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); // Add only throws when it has to do work. If, for some reason, this certificate // is already present in the CurrentUser\My store, we can't really test this // functionality. if (!store.Certificates.Contains(cert)) { Assert.ThrowsAny<CryptographicException>(() => store.Add(cert)); } } }
public static X509Certificate2 FindCertificateByThumbprint(string findValue) { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); try { store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, findValue, false); // Don't validate certs, since the test root isn't installed. if (col == null || col.Count == 0) return null; return col[0]; } finally { store.Close(); } }
private static void AddAuthHeader(HttpClient client, string audience = "http://www.enyu.com") { var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var signingCert = store.Certificates .Cast<X509Certificate2>() .FirstOrDefault(certificate => certificate.Subject == CertificateName); var tokenDescriptor = new SecurityTokenDescriptor { TokenIssuerName = "DMN", AppliesToAddress = audience, SigningCredentials = new X509SigningCredentials(signingCert) }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenString); }
public static int Main(string[] args) { X509Certificate2 cert = null ; X509Store store = null ; ArrayList al = new ArrayList() ; try { cert = TestCert ; store = new X509Store( StoreName.My , StoreLocation.CurrentUser ) ; store.Open( OpenFlags.ReadWrite ) ; store.Add( cert ) ; Test( X509IncludeOption.ExcludeRoot ) ; Test( X509IncludeOption.WholeChain ) ; Test( X509IncludeOption.EndCertOnly ) ; Test( (X509IncludeOption) 0xFFFF ) ; Test2() ; Test3() ; Test4() ; Test5() ; Test6() ; Test7() ; store.Remove( cert ) ; } catch( Exception e ) { rv = false ; Console.WriteLine( e.ToString() ) ; } finally { store.Close() ; } Console.WriteLine( rv ? "Test passed" : "Test failed" ) ; return rv ? 100 : 101 ; }
//Main method begins here. static void Main(string[] args) { //Test for correct number of arguments. if (args.Length < 1) { Console.WriteLine("Usage: CertInfo <filename>"); return; } try { X509Certificate2 x509 = new X509Certificate2(); //Create X509Certificate2 object from .cer file. byte[] rawData = ReadFile(args[0]); x509.Import(rawData); //Print to console information contained in the certificate. Console.WriteLine(x509.Thumbprint); //Add the certificate to a X509Store. X509Store store = new X509Store(); store.Open(OpenFlags.MaxAllowed); store.Add(x509); store.Close(); } catch (DirectoryNotFoundException) { Console.WriteLine("Error: The directory specified could not be found."); } catch (IOException) { Console.WriteLine("Error: A file in the directory could not be accessed."); } catch (NullReferenceException) { Console.WriteLine("File must be a .cer file. Program does not have access to that type of file."); } }
public HttpResponseMessage Get() { var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); try { var query = from cert in store.Certificates.Cast<X509Certificate2>() select new { cert.Subject, cert.FriendlyName, cert.Thumbprint }; return Request.CreateResponse(HttpStatusCode.OK, query.ToArray()); } finally { store.Close(); } }
public static HttpClient GetApiClientAsync(string contentType = "application/json") { X509Certificate2 cert = null; X509Store store = null; try { store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); } finally { if (store != null) store.Close(); } var baseUri = new Uri(OdataServiceUri); var clientHandler = new WebRequestHandler(); CredentialCache cc = new CredentialCache(); cc.Add(baseUri, "NTLM", CredentialCache.DefaultNetworkCredentials); clientHandler.Credentials = cc; if (cert != null) clientHandler.ClientCertificates.Add(cert); var client = new HttpClient(clientHandler) { BaseAddress = baseUri }; return client; }
/// this process runs in its own thread for the the full time of the hosting process. private void RunProcess(string keyName) { int threadID = Thread.GetCurrentProcessorId(); string whoami = Thread.CurrentPrincipal?.Identity?.ToString(); if (String.IsNullOrEmpty(whoami)) { whoami = Environment.GetEnvironmentVariable("USERNAME"); } _logger.LogInformation("Process Cred Store Service is runing on processor {0} and user {1}.", threadID, whoami); Thread.Sleep(200); // ensure the rest of the web server starts up bool bExists = CngKey.Exists(keyName); RSACng rsaKey; if (bExists) { CngKeyHandleOpenOptions ckhoo = new CngKeyHandleOpenOptions { }; cngKey = CngKey.Open(keyName); _logger.LogInformation("Found Key {0}.", keyName); X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine); certStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection certRes = certStore.Certificates.Find(X509FindType.FindBySubjectName, "Trustregistry", false); // X509Certificate2Enumerator certEnum = certRes.GetEnumerator(); foreach (X509Certificate2 x2 in certRes) { if (cert1 == null) { cert1 = x2; // TODO see if there are better choices than the first when i have some criteria } } certStore.Close(); } else { try { rsaKey = new RSACng(CngKey.Create(CngAlgorithm.Rsa, keyName, new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowExport })); cngKey = rsaKey.Key; RSAParameters rsaP = rsaKey.ExportParameters(true); X500DistinguishedName dn = new X500DistinguishedName("CN=Trustregistry.US", new X500DistinguishedNameFlags { }); CertificateRequest cr = new CertificateRequest(dn, rsaKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); _logger.LogInformation("Need to create a new Key named {0}.", keyName); } catch (Exception ex) { _logger.LogInformation("Exception trying to create a new Key named {0}, exception {1}.", keyName, ex.Message); } } if (cngKey != null) { try { keyType = cngKey.Algorithm; rsaKey = new RSACng(cngKey); X500DistinguishedName dnx = new X500DistinguishedName("CN=Trustregistry.US", new X500DistinguishedNameFlags { }); CertificateRequest crx = new CertificateRequest(dnx, rsaKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); X509Certificate2 cert2 = crx.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow + TimeSpan.FromHours(24 * 365.2 * 5)); // TODO get value from config IN HOURS // put that sert in the store X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine); certStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection certRes = certStore.Certificates.Find(X509FindType.FindBySubjectName, "Trustregistry", false); // X509Certificate2Enumerator certEnum = certRes.GetEnumerator(); foreach (X509Certificate2 x2 in certRes) { if (cert1 == null) { cert1 = x2; // TODO see if there are better choices than the first when i have some criteria } } // certStore.Add(cert2); certStore.Close(); } catch (Exception ex) { _logger.LogInformation("Exception trying to create a new cert for key named {0}, exception {1}.", keyName, ex.Message); } } while (true) { if (busy) { } Thread.Sleep(60000); // TODO make this event driven _logger.LogInformation("Process Cred Store Service still runing."); } }
/// ---------------------------------------------------------------------------------------- /// <summary> /// Helper method: Get array of certificate references and the according names from the passed certificate store. /// </summary> /// ---------------------------------------------------------------------------------------- public static ArrayList GetCertificatesAndNamesFromStore(ref ArrayList certificateNames, X509Store store) { ArrayList certificates = new ArrayList(); store.Open(OpenFlags.ReadOnly); foreach (X509Certificate2 x509Certificate in store.Certificates) { if (x509Certificate.HasPrivateKey) { certificates.Add(x509Certificate); if (!String.IsNullOrWhiteSpace(x509Certificate.FriendlyName)) { certificateNames.Add(x509Certificate.FriendlyName); } else if (!String.IsNullOrWhiteSpace(x509Certificate.SerialNumber)) { certificateNames.Add(x509Certificate.SerialNumber); } } } //Close the store. store.Close(); return(certificates); }
public static void DisableAiaOptionWorks() { CertificateAuthority.BuildPrivatePki( PkiOptions.AllRevocation, out RevocationResponder responder, out CertificateAuthority root, out CertificateAuthority intermediate, out X509Certificate2 endEntity, pkiOptionsInSubject: false); using (responder) using (root) using (intermediate) using (endEntity) using (ChainHolder holder = new ChainHolder()) using (X509Certificate2 rootCert = root.CloneIssuerCert()) using (X509Certificate2 intermediateCert = intermediate.CloneIssuerCert()) using (var cuCaStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser)) { cuCaStore.Open(OpenFlags.ReadWrite); X509Chain chain = holder.Chain; chain.ChainPolicy.DisableCertificateDownloads = true; chain.ChainPolicy.CustomTrustStore.Add(rootCert); chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; chain.ChainPolicy.VerificationTime = endEntity.NotBefore.AddMinutes(1); chain.ChainPolicy.UrlRetrievalTimeout = DynamicRevocationTests.s_urlRetrievalLimit; Assert.False(chain.Build(endEntity), "Chain build with no intermediate, AIA disabled"); // If a previous run of this test leaves contamination in the CU\CA store on Windows // the Windows chain engine will match the bad issuer and report NotSignatureValid instead // of PartialChain. X509ChainStatusFlags chainFlags = chain.AllStatusFlags(); if (chainFlags.HasFlag(X509ChainStatusFlags.NotSignatureValid)) { Assert.Equal(3, chain.ChainElements.Count); foreach (X509Certificate2 storeCert in cuCaStore.Certificates) { if (storeCert.Subject.Equals(intermediateCert.Subject)) { cuCaStore.Remove(storeCert); } storeCert.Dispose(); } holder.DisposeChainElements(); // Try again, with no caching side effect. Assert.False(chain.Build(endEntity), "Chain build 2 with no intermediate, AIA disabled"); } Assert.Equal(1, chain.ChainElements.Count); Assert.Contains(X509ChainStatusFlags.PartialChain, chain.ChainStatus.Select(s => s.Status)); holder.DisposeChainElements(); // macOS doesn't like our revocation responder, so disable revocation checks there. if (PlatformDetection.IsOSX) { chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; } chain.ChainPolicy.ExtraStore.Add(intermediateCert); Assert.True(chain.Build(endEntity), "Chain build with intermediate, AIA disabled"); Assert.Equal(3, chain.ChainElements.Count); Assert.Equal(X509ChainStatusFlags.NoError, chain.AllStatusFlags()); holder.DisposeChainElements(); chain.ChainPolicy.DisableCertificateDownloads = false; chain.ChainPolicy.ExtraStore.Clear(); Assert.True(chain.Build(endEntity), "Chain build with no intermediate, AIA enabled"); Assert.Equal(3, chain.ChainElements.Count); Assert.Equal(X509ChainStatusFlags.NoError, chain.AllStatusFlags()); cuCaStore.Remove(intermediateCert); } }
public new SSLCertificate InstallCertificate(SSLCertificate cert, WebSite website) { try { var response = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment", true)) as CX509Enrollment; if (response == null) { throw new Exception("Cannot create instance of X509Enrollment.CX509Enrollment"); } response.Initialize(X509CertificateEnrollmentContext.ContextMachine); response.InstallResponse( InstallResponseRestrictionFlags.AllowUntrustedRoot, cert.Certificate, EncodingType.XCN_CRYPT_STRING_BASE64HEADER, null ); // At this point, certificate has been installed into "Personal" store // We need to move it into "WebHosting" store // Get certificate var servercert = GetServerCertificates(StoreName.My.ToString()).Single(c => c.FriendlyName == cert.FriendlyName); // Get certificate data - the one we just added to "Personal" store var storeMy = new X509Store(StoreName.My, StoreLocation.LocalMachine); storeMy.Open(OpenFlags.MaxAllowed); X509CertificateCollection existCerts2 = storeMy.Certificates.Find(X509FindType.FindBySerialNumber, servercert.SerialNumber, false); var certData = existCerts2[0].Export(X509ContentType.Pfx); storeMy.Close(); var x509Cert = new X509Certificate2(certData, string.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); if (UseCCS) { // Revert to InstallPfx to install new certificate - this also adds binding InstallPfx(certData, string.Empty, website); } else { // Add new certificate to "WebHosting" store var store = new X509Store(CertificateStoreName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(x509Cert); store.Close(); } // Remove certificate from "Personal" store storeMy.Open(OpenFlags.MaxAllowed); X509CertificateCollection existCerts = storeMy.Certificates.Find(X509FindType.FindBySerialNumber, servercert.SerialNumber, false); storeMy.Remove((X509Certificate2)existCerts[0]); storeMy.Close(); // Fill object with certificate data cert.SerialNumber = servercert.SerialNumber; cert.ValidFrom = servercert.ValidFrom; cert.ExpiryDate = servercert.ExpiryDate; cert.Hash = servercert.Hash; cert.DistinguishedName = servercert.DistinguishedName; if (!UseCCS) { if (CheckCertificate(website)) { DeleteCertificate(GetCurrentSiteCertificate(website), website); } AddBinding(x509Cert, website); } } catch (Exception ex) { Log.WriteError("Error adding SSL certificate", ex); cert.Success = false; } return(cert); }
private bool M_FindCertByFriendlyName(string FriendlyNameToFind, StoreName CertStoreName, StoreLocation CertStoreLocation, ref X509Certificate2 ReturnCertificate, bool CheckPrivateKey = false) { //Wyjście bool jestCert = false; //Otwarcie kontenera z certyfikatami X509Store keystore = new X509Store(CertStoreName, CertStoreLocation); keystore.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificates = keystore.Certificates; foreach (var certificate in certificates) { var friendlyNameFromCert = certificate.FriendlyName; if (friendlyNameFromCert == FriendlyNameToFind) { //Czy nie jest przeterminowany string certExpiratioDate = certificate.GetExpirationDateString(); if (certificate.NotAfter <= DateTime.Now) { textBox1.AppendText("Pomijam certyfikat - przyjazna nazwa: " + certificate.FriendlyName + Environment.NewLine); textBox1.AppendText(" Pomijam certyfikat - Wystawiono dla: " + certificate.SubjectName.Name + Environment.NewLine); textBox1.AppendText(" Pomijam certyfikat - Wystawca: " + certificate.Issuer + Environment.NewLine); textBox1.AppendText(" Pomijam certyfikat - WYGASŁ: " + certExpiratioDate + Environment.NewLine); continue; } else { textBox1.AppendText("Certyfikat - Przyjazna nazwa: " + certificate.FriendlyName + Environment.NewLine); textBox1.AppendText(" Certyfikat - Wystawiono dla: " + certificate.SubjectName.Name + Environment.NewLine); textBox1.AppendText(" Certyfikat - Wystawca: " + certificate.Issuer + Environment.NewLine); textBox1.AppendText(" Certyfikat - Aktualny, ważny do: " + certExpiratioDate + Environment.NewLine); ReturnCertificate = certificate; //Czy mam sprawdzać klucz prywatny if (CheckPrivateKey == true) { if (ReturnCertificate.HasPrivateKey == true) { jestCert = true; break; } else { jestCert = false; textBox1.AppendText(" Pomijam certyfikat - BRAK KLUCZA PRYWATNEGO!!! " + Environment.NewLine); //Szukam dalej continue; } } else { jestCert = true; break; } } } } keystore.Close(); if (!jestCert) { MessageBox.Show("Nie znalazłem certyfikatu klienta wg FriendlyName: " + FriendlyNameToFind); } return(jestCert); }
private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri) { // Must be HTTPS scheme to use client certificates. if (requestUri.Scheme != UriSchemeHttps) { return; } // Get candidate list for client certificates. X509Certificate2Collection certs; if (_clientCertificateOption == ClientCertificateOption.Manual) { certs = ClientCertificates; } else { using (var myStore = new X509Store()) { myStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); certs = myStore.Certificates; } } // Check for no certs now as a performance optimization. if (certs.Count == 0) { SetNoClientCertificate(requestHandle); return; } // Reduce the set of certificates to match the proper 'Client Authentication' criteria. certs = certs.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, true); certs = certs.Find(X509FindType.FindByApplicationPolicy, ClientAuthenticationOID, true); // Build a new collection with certs that have a private key. Need to do this // manually because there is no X509FindType to match this criteria. var clientCerts = new X509Certificate2Collection(); foreach (var cert in certs) { if (cert.HasPrivateKey) { clientCerts.Add(cert); } } // TOOD: Filter the list based on TrustedIssuerList info from WINHTTP. // Set the client certificate. if (certs.Count == 0) { SetNoClientCertificate(requestHandle); } else { SetWinHttpOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT, clientCerts[0].Handle, (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>()); } }
static void Main(string[] args) { string password = null; Header(); if (args.Length < 2) { Help(); return; } Action action = GetAction(args [0]); ObjectType type = ObjectType.None; int n = 1; if (action != Action.Ssl) { type = GetObjectType(args [n]); if (type != ObjectType.None) { n++; } } bool verbose = (GetCommand(args [n]) == "V"); if (verbose) { n++; } bool machine = (GetCommand(args [n]) == "M"); if (machine) { n++; } if (GetCommand(args [n]) == "P") { n++; password = args[n++]; } X509Store store = null; string storeName = null; if (action != Action.Ssl) { if ((action == Action.None) || (type == ObjectType.None)) { Help(); return; } if (type == ObjectType.CTL) { Console.WriteLine("CTL are not supported"); return; } storeName = args [n++]; store = GetStoreFromName(storeName, machine); if (store == null) { Console.WriteLine("Invalid Store: {0}", storeName); Console.WriteLine("Valid stores are: {0}, {1}, {2}, {3} and {4}", X509Stores.Names.Personal, X509Stores.Names.OtherPeople, X509Stores.Names.IntermediateCA, X509Stores.Names.TrustedRoot, X509Stores.Names.Untrusted); return; } } string file = (n < args.Length) ? args [n] : null; // now action! try { switch (action) { case Action.Add: Add(type, store, file, password, verbose); break; case Action.Delete: Delete(type, store, file, verbose); break; case Action.Put: Put(type, store, file, password, verbose); break; case Action.List: List(type, store, machine, file, verbose); break; case Action.Ssl: Ssl(file, machine, verbose); break; case Action.ImportKey: ImportKey(type, machine, file, password, verbose); break; default: throw new NotSupportedException(action.ToString()); } } catch (UnauthorizedAccessException uae) { Console.WriteLine("Access to the {0} '{1}' certificate store has been denied.", (machine ? "machine" : "user"), storeName); if (verbose) { Console.WriteLine(uae); } } }
public void SetUp() { this.underTest = new X509Store(StoreName.My, StoreLocation.CurrentUser); this.underTest.Open(OpenFlags.ReadWrite); }
public void ConfigureServices(IServiceCollection services) { var stsConfig = Configuration.GetSection("StsConfig"); _clientId = Configuration["MicrosoftClientId"]; _clientSecret = Configuration["MircosoftClientSecret"]; var useLocalCertStore = Convert.ToBoolean(Configuration["UseLocalCertStore"]); var certificateThumbprint = Configuration["CertificateThumbprint"]; X509Certificate2 cert; if (_environment.IsProduction()) { if (useLocalCertStore) { using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadOnly); var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false); cert = certs[0]; store.Close(); } } else { // Azure deployment, will be used if deployed to Azure var vaultConfigSection = Configuration.GetSection("Vault"); var keyVaultService = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]); cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]); } } else { cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "sts_dev_cert.pfx"), "1234"); } services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder .AllowCredentials() .WithOrigins("https://localhost:44356", "https://localhost:44357") .SetIsOriginAllowedToAllowWildcardSubdomains() .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); services.Configure <StsConfig>(Configuration.GetSection("StsConfig")); services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings")); services.AddSingleton <LocService>(); services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <ApplicationDbContext>() .AddErrorDescriber <StsIdentityErrorDescriber>() .AddDefaultTokenProviders(); services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>(); services.AddTransient <IEmailSender, EmailSender>(); services.AddAuthentication() .AddOpenIdConnect("aad", "Login with Azure AD", options => { options.Authority = $"https://login.microsoftonline.com/common"; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false }; options.ClientId = "99eb0b9d-ca40-476e-b5ac-6f4c32bfb530"; options.CallbackPath = "/signin-oidc"; }); services.AddAuthorization(); services.Configure <RequestLocalizationOptions>( options => { var supportedCultures = new List <CultureInfo> { new CultureInfo("en-US"), new CultureInfo("de-CH"), new CultureInfo("fr-CH"), new CultureInfo("it-CH") }; options.DefaultRequestCulture = new RequestCulture(culture: "de-CH", uiCulture: "de-CH"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; var providerQuery = new LocalizationQueryProvider { QureyParamterName = "ui_locales" }; options.RequestCultureProviders.Insert(0, providerQuery); }); services.AddControllersWithViews(options => { options.Filters.Add(new SecurityHeadersAttribute()); }) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddViewLocalization() .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => { var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName); return(factory.Create("SharedResource", assemblyName.Name)); }; }); services.AddIdentityServer() .AddSigningCredential(cert) .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiResources(Config.GetApiResources()) .AddInMemoryClients(Config.GetClients()) .AddAspNetIdentity <ApplicationUser>() .AddProfileService <IdentityWithAdditionalClaimsProfileService>(); }
private string ServerCertValidate() { string errorMessage = String.Empty; X509Store store = WorkContext.IsMono ? X509StoreManager.CurrentUser.TrustedRoot : X509StoreManager.LocalMachine.TrustedRoot; try { var storage = StorageFactory.GetStorage("-1", "certs"); // Import the details of the certificate from the server. X509Certificate x509 = null; lock (rootSync) { if (certificate != null) { var data = certificate.GetRawCertData(); x509 = new X509Certificate(data); } } if (x509 != null) { // Check for ceritficate in store. if (!store.Certificates.Contains(x509)) { if (storage.IsFile("ldap/ldap.cer")) { var storageData = GetCertificateFromStorage(storage); var storageX509 = new X509Certificate(storageData); if (CompareHash(storageX509.Hash, x509.Hash)) { // Add the certificate to the store. store.Import(storageX509); store.Certificates.Add(storageX509); return(String.Empty); } } errorMessage = String.Format("LDAP TlsHandler. Certificate not found in certificate store. {0}.", x509.IssuerName); log.Error(errorMessage); return(errorMessage); } log.DebugFormat("LDAP TlsHandler. Certificate found in certificate store. {0}.", x509.IssuerName); } else { // for AD if (storage.IsFile("ldap/ldap.cer")) { var storageData = GetCertificateFromStorage(storage); var storageX509 = new X509Certificate(storageData); // Add the certificate to the store. store.Import(storageX509); store.Certificates.Add(storageX509); return(String.Empty); } else { errorMessage = "LDAP TlsHandler. Certificate not found in certificate store."; log.Error(errorMessage); return(errorMessage); } } return(String.Empty); } catch (Exception ex) { errorMessage = String.Format("LDAP TlsHandler. Error: {0}. {1}.", ex.ToString(), ex.InnerException != null ? ex.InnerException.ToString() : string.Empty); log.Error(errorMessage); return(errorMessage); } }
internal static HashSet <X509Certificate2> FindCandidates( X509Certificate2 leaf, X509Certificate2Collection extraStore, HashSet <X509Certificate2> downloaded, HashSet <X509Certificate2> systemTrusted, ref TimeSpan remainingDownloadTime) { var candidates = new HashSet <X509Certificate2>(); var toProcess = new Queue <X509Certificate2>(); toProcess.Enqueue(leaf); using (var systemRootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) using (var systemIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine)) using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser)) using (var userIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser)) { systemRootStore.Open(OpenFlags.ReadOnly); systemIntermediateStore.Open(OpenFlags.ReadOnly); userRootStore.Open(OpenFlags.ReadOnly); userIntermediateStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection systemRootCerts = systemRootStore.Certificates; X509Certificate2Collection systemIntermediateCerts = systemIntermediateStore.Certificates; X509Certificate2Collection userRootCerts = userRootStore.Certificates; X509Certificate2Collection userIntermediateCerts = userIntermediateStore.Certificates; // fill the system trusted collection foreach (X509Certificate2 userRootCert in userRootCerts) { if (!systemTrusted.Add(userRootCert)) { // If we have already (effectively) added another instance of this certificate, // then this one provides no value. A Disposed cert won't harm the matching logic. userRootCert.Dispose(); } } foreach (X509Certificate2 systemRootCert in systemRootCerts) { if (!systemTrusted.Add(systemRootCert)) { // If we have already (effectively) added another instance of this certificate, // (for example, because another copy of it was in the user store) // then this one provides no value. A Disposed cert won't harm the matching logic. systemRootCert.Dispose(); } } X509Certificate2Collection[] storesToCheck = { extraStore, userIntermediateCerts, systemIntermediateCerts, userRootCerts, systemRootCerts, }; while (toProcess.Count > 0) { X509Certificate2 current = toProcess.Dequeue(); candidates.Add(current); HashSet <X509Certificate2> results = FindIssuer( current, storesToCheck, downloaded, ref remainingDownloadTime); if (results != null) { foreach (X509Certificate2 result in results) { if (!candidates.Contains(result)) { toProcess.Enqueue(result); } } } } // Avoid sending unused certs into the finalizer queue by doing only a ref check var candidatesByReference = new HashSet <X509Certificate2>( candidates, ReferenceEqualityComparer <X509Certificate2> .Instance); // Certificates come from 5 sources: // 1) extraStore. // These are cert objects that are provided by the user, we shouldn't dispose them. // 2) the machine root store // These certs are moving on to the "was I a system trust?" test, and we shouldn't dispose them. // 3) the user root store // These certs are moving on to the "was I a system trust?" test, and we shouldn't dispose them. // 4) the machine intermediate store // These certs were either path candidates, or not. If they were, don't dispose them. Otherwise do. // 5) the user intermediate store // These certs were either path candidates, or not. If they were, don't dispose them. Otherwise do. DisposeUnreferenced(candidatesByReference, systemIntermediateCerts); DisposeUnreferenced(candidatesByReference, userIntermediateCerts); } return(candidates); }
internal static void EnsureInited() { if (!_didInit) { lock (_initLock) { #if IS_UNITY var nonSniRootCa = new X509Certificate2(System.Convert.FromBase64String(@" MIIGNjCCBB6gAwIBAgIJAIFAzu/SSMPWMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYD VQQGEwJBVTERMA8GA1UECAwIVmljdG9yaWExHzAdBgNVBAoMFlJlZHBvaW50IEdh bWVzIFB0eSBMdGQxPDA6BgNVBAsMM1JlZHBvaW50IEdhbWVzIFB0eSBMdGQgTm8t U05JIENlcnRpZmljYXRlIEF1dGhvcml0eTEmMCQGA1UEAwwdUmVkcG9pbnQgR2Ft ZXMgTm8tU05JIFJvb3QgQ0EwHhcNMTgwMjE2MDQwNTE0WhcNMzgwMjExMDQwNTE0 WjCBpzELMAkGA1UEBhMCQVUxETAPBgNVBAgMCFZpY3RvcmlhMR8wHQYDVQQKDBZS ZWRwb2ludCBHYW1lcyBQdHkgTHRkMTwwOgYDVQQLDDNSZWRwb2ludCBHYW1lcyBQ dHkgTHRkIE5vLVNOSSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkxJjAkBgNVBAMMHVJl ZHBvaW50IEdhbWVzIE5vLVNOSSBSb290IENBMIICIjANBgkqhkiG9w0BAQEFAAOC Ag8AMIICCgKCAgEA0rFk0tWyHoustnvIjaD4DK9eiSelMzei03vyJHwzGvr3Gb8q xP0rotPFDPtP3OQD9mHkvfN44pxKJhulT7bGYqvHp1uB6/gDfjdK7etKI6pY3NeE Vv+sflsc+bHJ0JAHuMJUA439qeekhHg+85W7IIOGhul0V2Onm9sg0hfmai7+xy28 bgxiw3aWuywl+3+fqFSJGWmtkkTHqN9FCiil6KSwcfa6GIiHk140PRsV4O4XtuFs B0XUbhwG//6w7VfCPHDhtzmrDMTbPrQq8M6CUdp5cH8CrN48nSpw0mrt+ILF0qR9 t6CQXx2e9CebWFYEEiqDLJtFnO/gDiaQPhZTs1M0PQ4Q5L2VUQajLjxbEcWGo0FH etoatE+p7So4lZGHD1pSlau91kgkkkP38TynyozGvLyND3eWmfNa0Qfb7YQma0Nl O6ezYZs4RNPE+P1lZsY/9+3KpnlWRHVfEp8VjEGBdJnpwUcs+Ys9qpS5Fs0yvCqY HEUuzgrfaOyl0F9A9WXD3rFZI1KWh7olbF5oV+c7o996r0VSMJ3XPKC72iWGONux ddtFcGBRtIASZSkPuFNfOl2ARjqOAcy3//6XLX2nHW9YwDo+FEJhnR26tk5VpfmW t/qMQ+BUmBPer+HYCtv2lSss/hxAxaiToo1IiVhQ4/XEQZgasa7I9neSR3kCAwEA AaNjMGEwHQYDVR0OBBYEFPZeVoLdOgtxffUhY3fEcO6oKD8nMB8GA1UdIwQYMBaA FPZeVoLdOgtxffUhY3fEcO6oKD8nMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQBr+gv2FNFFDsM1TsdrP0Featjc41pI iN/zRA5+UMSx8svIoQ68GDbcAC1jm96yxkjcn5TkUQknpwP7vo2GzO6+bPz4zbKZ TYOn8oxuxAAvXm/+1YfSGNnuC5U+yPyg5cl8PhOuZgBlGXXhHi7e7bvyPzlHq9Ni 5BcsHiGYho8eTNbRRWVdmE+NA9ievyLP/sFiYbvJiEfprSMI5z2SwQF6PE2q9/DD 2BH9SLn+xf2NdVoGah76/ucbEou0XNzE66I8cQa/VNjm4Ks+iRBO4e2TVW+eMpQd /JAvsv7eEgaOaadJL82dHIzG1lLh6KS+jIQF2lRfRtA7DSG4R6LBIMKltLdF7gyr m8dChiCLeovbiLGch4qGohVTRfxCL4u8xmQKaftuuDJXZsEXEm8ihkvy6AoyAR7W W0953oCT0ydWCF8C6FhBUSdkDBzctk/rdUdbpNmK4OzUsx9pnAfya1FRpjylh4KS ZDottbiPxLyy7YOa7AWtAqEE6MmDAKLFw9tlecODSugWvu3ZZAZXARpS5z5IxSVU wgXFr7o7U/FQ1xmjmlDPVkCMBnN2wVctJIJMHHm4RejLPf5aaLUXVgB48Ce0Jd+1 aLQ9T0/BMgxvrq09V8sSV+j7tnJDI3NXvujdGx6WQ/yDU/A62D9D3wgznN2aHJOg Rx77b+JypsJMRA==".Replace("\r\n", "").Replace("\n", ""))); var store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); try { store.Open(OpenFlags.ReadWrite); store.Add(nonSniRootCa); } finally { store.Close(); } // Validate requests using our No-SNI certificate, because Unity doesn't support any kind // of modern SSL. ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return HiveMPCertificateValidation(sender, certificate, chain, sslPolicyErrors, nonSniRootCa); }; #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX) && NET_4_6 && UNITY_2017_2_OR_NEWER System.Environment.SetEnvironmentVariable("MONO_TLS_PROVIDER", "legacy"); #endif #endif #if ENABLE_CLIENT_CONNECT_SDK SetupClientConnect(); #endif _didInit = true; } } }
public static void TryInstallingCertificate_PromptForKey() { try { string CertificateFilename; if (ShowOpenFileDialog(CertificatesFilter, "Choose a code signing certificate to import", "", "", ref ChoosingFilesToInstallDirectory, out CertificateFilename)) { // Load the certificate string CertificatePassword = ""; X509Certificate2 Cert = null; try { Cert = new X509Certificate2(CertificateFilename, CertificatePassword, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); } catch (System.Security.Cryptography.CryptographicException ex) { // Try once with a password if (PasswordDialog.RequestPassword(out CertificatePassword)) { Cert = new X509Certificate2(CertificateFilename, CertificatePassword, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); } else { // User cancelled dialog, rethrow throw ex; } } // If the certificate doesn't have a private key pair, ask the user to provide one if (!Cert.HasPrivateKey) { string ErrorMsg = "Certificate does not include a private key and cannot be used to code sign"; // Prompt for a key pair if (MessageBox.Show("Next, please choose the key pair that you made when generating the certificate request.", Config.AppDisplayName, MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK) { string KeyFilename; if (ShowOpenFileDialog(KeysFilter, "Choose the key pair that belongs with the signing certificate", "", "", ref ChoosingFilesToInstallDirectory, out KeyFilename)) { Cert = CryptoAdapter.CombineKeyAndCert(CertificateFilename, KeyFilename); if (Cert.HasPrivateKey) { ErrorMsg = null; } } } if (ErrorMsg != null) { throw new Exception(ErrorMsg); } } // Add the certificate to the store X509Store Store = new X509Store(); Store.Open(OpenFlags.ReadWrite); Store.Add(Cert); Store.Close(); } } catch (Exception ex) { string ErrorMsg = String.Format("Failed to load or install certificate due to an error: '{0}'", ex.Message); Program.Error(ErrorMsg); MessageBox.Show(ErrorMsg, Config.AppDisplayName, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public SSLCertificate InstallPfx(byte[] certificate, string password, WebSite website) { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); // SSLCertificate newcert = null, oldcert = null; // Ensure we perform operations safely and preserve the original state during all manipulations if (CheckCertificate(website)) { oldcert = GetCurrentSiteCertificate(website); } // X509Certificate2 x509Cert = new X509Certificate2(certificate, password); #region Step 1: Register X.509 certificate in the store // Trying to keep X.509 store open as less as possible try { store.Open(OpenFlags.ReadWrite); // store.Add(x509Cert); } catch (Exception ex) { Log.WriteError(String.Format("SSLModuleService could not import PFX into X509Store('{0}', '{1}')", store.Name, store.Location), ex); // Re-throw error throw; } finally { store.Close(); } #endregion #region Step 2: Instantiate a copy of new X.509 certificate try { // store.Open(OpenFlags.ReadWrite); // newcert = new SSLCertificate { Hostname = x509Cert.GetNameInfo(X509NameType.SimpleName, false), FriendlyName = x509Cert.FriendlyName, CSRLength = Convert.ToInt32(x509Cert.PublicKey.Key.KeySize.ToString()), Installed = true, DistinguishedName = x509Cert.Subject, Hash = x509Cert.GetCertHash(), SerialNumber = x509Cert.SerialNumber, ExpiryDate = DateTime.Parse(x509Cert.GetExpirationDateString()), ValidFrom = DateTime.Parse(x509Cert.GetEffectiveDateString()), }; } catch (Exception ex) { // Rollback X.509 store changes store.Remove(x509Cert); // Log error Log.WriteError("SSLModuleService could not instantiate a copy of new X.509 certificate. All previous changes have been rolled back.", ex); // Re-throw throw; } finally { store.Close(); } #endregion #region Step 3: Remove old certificate from the web site if any try { store.Open(OpenFlags.ReadWrite); // Check if certificate already exists, remove it. if (oldcert != null) { DeleteCertificate(oldcert, website); } } catch (Exception ex) { // Rollback X.509 store changes store.Remove(x509Cert); // Log the error Log.WriteError( String.Format("SSLModuleService could not remove existing certificate from '{0}' web site. All changes have been rolled back.", website.Name), ex); // Re-throw throw; } finally { store.Close(); } #endregion #region Step 4: Register new certificate with HTTPS binding on the web site try { store.Open(OpenFlags.ReadWrite); // AddBinding(newcert, website); } catch (Exception ex) { // Install old certificate back if any if (oldcert != null) { InstallCertificate(oldcert, website); } // Rollback X.509 store changes store.Remove(x509Cert); // Log the error Log.WriteError( String.Format("SSLModuleService could not add new X.509 certificate to '{0}' web site. All changes have been rolled back.", website.Name), ex); // Re-throw throw; } finally { store.Close(); } #endregion // return(newcert); }
/// <summary> /// Verify package signature /// </summary> private bool VerifyPackage(AppletPackage package) { byte[] verifyBytes = package.Manifest; // First check: Hash - Make sure the HASH is ok if (package is AppletSolution) { verifyBytes = (package as AppletSolution).Include.SelectMany(o => o.Manifest).ToArray(); if (BitConverter.ToString(SHA256.Create().ComputeHash(verifyBytes)) != BitConverter.ToString(package.Meta.Hash)) { throw new InvalidOperationException($"Package contents of {package.Meta.Id} appear to be corrupt!"); } } else if (BitConverter.ToString(SHA256.Create().ComputeHash(package.Manifest)) != BitConverter.ToString(package.Meta.Hash)) { throw new InvalidOperationException($"Package contents of {package.Meta.Id} appear to be corrupt!"); } if (package.Meta.Signature != null) { this.m_tracer.TraceInfo("Will verify package {0}", package.Meta.Id.ToString()); // Get the public key var x509Store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine); try { x509Store.Open(OpenFlags.ReadOnly); var cert = x509Store.Certificates.Find(X509FindType.FindByThumbprint, package.Meta.PublicKeyToken, false); if (cert.Count == 0) { if (package.PublicKey != null) { // Embedded cert and trusted CA X509Certificate2 embCert = new X509Certificate2(package.PublicKey); // Not explicitly trusted to we need to build a chain if (!this.m_caIssuerCert.Subject.Equals(embCert.Issuer) && !this.m_configuration.TrustedPublishers.Contains(embCert.Thumbprint)) { // Build the certificate chain var embChain = new X509Chain(); embChain.Build(embCert); // Validate the chain elements if possible bool isTrusted = false; foreach (var itm in embChain.ChainElements) { isTrusted |= this.m_configuration.TrustedPublishers.Contains(itm.Certificate.Thumbprint); } if (!isTrusted || embChain.ChainStatus.Any(o => o.Status != X509ChainStatusFlags.RevocationStatusUnknown) && !this.m_configuration.TrustedPublishers.Contains(embCert.Issuer)) { throw new SecurityException($"Cannot verify identity of publisher {embCert.Subject}"); } else { cert = new X509Certificate2Collection(embCert); } } else { cert = new X509Certificate2Collection(embCert); } } else { throw new SecurityException($"Cannot find public key of publisher information for {package.Meta.PublicKeyToken} or the local certificate is invalid"); } } // Verify signature RSACryptoServiceProvider rsa = cert[0].PublicKey.Key as RSACryptoServiceProvider; var retVal = rsa.VerifyData(verifyBytes, CryptoConfig.MapNameToOID("SHA1"), package.Meta.Signature); // Verify timestamp var timestamp = package.Unpack().Info.TimeStamp; if (timestamp > DateTime.Now) { throw new SecurityException($"Package {package.Meta.Id} was published in the future! Something's fishy, refusing to load"); } else if (cert[0].NotAfter <timestamp || cert[0].NotBefore> timestamp) { throw new SecurityException($"Cannot find public key of publisher information for {package.Meta.PublicKeyToken} or the local certificate is invalid"); } if (retVal == true) { this.m_tracer.TraceEvent(EventLevel.Informational, "SUCCESSFULLY VALIDATED: {0} v.{1}\r\n" + "\tKEY TOKEN: {2}\r\n" + "\tSIGNED BY: {3}\r\n" + "\tVALIDITY: {4:yyyy-MMM-dd} - {5:yyyy-MMM-dd}\r\n" + "\tISSUER: {6}", package.Meta.Id, package.Meta.Version, cert[0].Thumbprint, cert[0].Subject, cert[0].NotBefore, cert[0].NotAfter, cert[0].Issuer); } else { this.m_tracer.TraceEvent(EventLevel.Critical, ">> SECURITY ALERT : {0} v.{1} <<\r\n" + "\tPACKAGE HAS BEEN TAMPERED WITH\r\n" + "\tKEY TOKEN (CLAIMED): {2}\r\n" + "\tSIGNED BY (CLAIMED): {3}\r\n" + "\tVALIDITY: {4:yyyy-MMM-dd} - {5:yyyy-MMM-dd}\r\n" + "\tISSUER: {6}\r\n\tSERVICE WILL HALT", package.Meta.Id, package.Meta.Version, cert[0].Thumbprint, cert[0].Subject, cert[0].NotBefore, cert[0].NotAfter, cert[0].Issuer); } return(retVal); } finally { x509Store.Close(); } } else if (this.m_configuration.AllowUnsignedApplets) { this.m_tracer.TraceEvent(EventLevel.Warning, "Package {0} v.{1} (publisher: {2}) is not signed. To prevent unsigned applets from being installed disable the configuration option", package.Meta.Id, package.Meta.Version, package.Meta.Author); return(true); } else { this.m_tracer.TraceEvent(EventLevel.Critical, "Package {0} v.{1} (publisher: {2}) is not signed and cannot be installed", package.Meta.Id, package.Meta.Version, package.Meta.Author); return(false); } }
/// ---------------------------------------------------------------------------------------- /// <summary> /// Helper method: Search passed store for certificate with passed public key hash. /// </summary> /// ---------------------------------------------------------------------------------------- public static X509Certificate2 GetCertificateFromPassedStore(byte[] publicKeyHash, X509Store store) { X509Certificate2 sebCertificate = null; store.Open(OpenFlags.ReadOnly); foreach (X509Certificate2 x509Certificate in store.Certificates) { byte[] publicKeyRawData = x509Certificate.PublicKey.EncodedKeyValue.RawData; SHA1 sha = new SHA1CryptoServiceProvider(); byte[] certificateHash = sha.ComputeHash(publicKeyRawData); //certificateName = x509Certificate.Subject; if (certificateHash.SequenceEqual(publicKeyHash)) { sebCertificate = x509Certificate; break; } } //Close the store. store.Close(); return(sebCertificate); }
public override void Execute() { if (!CanRunOnPlatform()) { return; } Start(); Truncate(runId); // On Windows we can use the .NET API to iterate through all the stores. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { foreach (StoreLocation storeLocation in (StoreLocation[])Enum.GetValues(typeof(StoreLocation))) { foreach (StoreName storeName in (StoreName[])Enum.GetValues(typeof(StoreName))) { try { X509Store store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); foreach (X509Certificate2 certificate in store.Certificates) { Write(storeLocation, storeName, certificate); } store.Close(); } catch (Exception e) { Log.Debug(e.StackTrace); Log.Debug(e.GetType().ToString()); Log.Debug(e.Message); Telemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e); } } } } // On linux we check the central trusted root store (a folder), which has symlinks to actual cert locations scattered across the db // We list all the certificates and then create a new X509Certificate2 object for each by filename. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { var result = ExternalCommandRunner.RunExternalCommand("ls", new string[] { "/etc/ssl/certs", "-A" }); Log.Debug("{0}", result); foreach (var _line in result.Split('\n')) { Log.Debug("{0}", _line); try { X509Certificate2 cert = new X509Certificate2("/etc/ssl/certs/" + _line); Write(StoreLocation.LocalMachine, StoreName.Root, cert); } catch (Exception e) { Log.Debug("{0} {1} Issue creating certificate based on /etc/ssl/certs/{2}", e.GetType().ToString(), e.Message, _line); Log.Debug("{0}", e.StackTrace); } } } // On macos we use the keychain and export the certificates as .pem. // However, on macos Certificate2 doesn't support loading from a pem, // so first we need pkcs12s instead, we convert using openssl, which requires we set a password // we import the pkcs12 with all our certs, delete the temp files and then iterate over it the certs else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var result = ExternalCommandRunner.RunExternalCommand("security", new string[] { "find-certificate", "-ap", "/System/Library/Keychains/SystemRootCertificates.keychain" }); string tmpPath = Path.Combine(Directory.GetCurrentDirectory(), "tmpcert.pem"); string pkPath = Path.Combine(Directory.GetCurrentDirectory(), "tmpcert.pk12"); File.WriteAllText(tmpPath, result); _ = ExternalCommandRunner.RunExternalCommand("openssl", new string[] { "pkcs12", "-export", "-nokeys", "-out", pkPath, "-passout pass:pass", "-in", tmpPath }); X509Certificate2Collection xcert = new X509Certificate2Collection(); xcert.Import(pkPath, "pass", X509KeyStorageFlags.DefaultKeySet); File.Delete(tmpPath); File.Delete(pkPath); var X509Certificate2Enumerator = xcert.GetEnumerator(); while (X509Certificate2Enumerator.MoveNext()) { Write(StoreLocation.LocalMachine, StoreName.Root, X509Certificate2Enumerator.Current); } } DatabaseManager.Commit(); Stop(); }
internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyInfoX509Data, CertUsageType certUsageType) { X509Certificate2Collection collection = new X509Certificate2Collection(); ArrayList decryptionIssuerSerials = (certUsageType == CertUsageType.Decryption ? new ArrayList() : null); if (keyInfoX509Data.Certificates != null) { foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates) { switch (certUsageType) { case CertUsageType.Verification: collection.Add(certificate); break; case CertUsageType.Decryption: decryptionIssuerSerials.Add(CreateX509IssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber)); break; } } } if (keyInfoX509Data.SubjectNames == null && keyInfoX509Data.IssuerSerials == null && keyInfoX509Data.SubjectKeyIds == null && decryptionIssuerSerials == null) { return(collection); } // Open LocalMachine and CurrentUser "Other People"/"My" stores. X509Store[] stores = new X509Store[2]; string storeName = (certUsageType == CertUsageType.Verification ? "AddressBook" : "My"); stores[0] = new X509Store(storeName, StoreLocation.CurrentUser); stores[1] = new X509Store(storeName, StoreLocation.LocalMachine); for (int index = 0; index < stores.Length; index++) { if (stores[index] != null) { X509Certificate2Collection filters = null; // We don't care if we can't open the store. try { stores[index].Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); filters = stores[index].Certificates; stores[index].Close(); if (keyInfoX509Data.SubjectNames != null) { foreach (string subjectName in keyInfoX509Data.SubjectNames) { filters = filters.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false); } } if (keyInfoX509Data.IssuerSerials != null) { foreach (X509IssuerSerial issuerSerial in keyInfoX509Data.IssuerSerials) { filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false); filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false); } } if (keyInfoX509Data.SubjectKeyIds != null) { foreach (byte[] ski in keyInfoX509Data.SubjectKeyIds) { string hex = EncodeHexString(ski); filters = filters.Find(X509FindType.FindBySubjectKeyIdentifier, hex, false); } } if (decryptionIssuerSerials != null) { foreach (X509IssuerSerial issuerSerial in decryptionIssuerSerials) { filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false); filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false); } } } // Store doesn't exist, no read permissions, other system error catch (CryptographicException) { } // Opening LocalMachine stores (other than Root or CertificateAuthority) on Linux catch (PlatformNotSupportedException) { } if (filters != null) { collection.AddRange(filters); } } } return(collection); }
/// <summary> /// Retrieves a collection containing the client SSL PFX certificates. /// </summary> /// <remarks>Dependent on connection string settings. /// Either file or store based certificates are used.</remarks> private X509CertificateCollection GetPFXClientCertificates() { X509CertificateCollection certs = new X509CertificateCollection(); // Check for file-based certificate if (_settings.CertificateFile != null) { X509Certificate2 clientCert = new X509Certificate2(_settings.CertificateFile, _settings.CertificatePassword); certs.Add(clientCert); return(certs); } if (_settings.CertificateStoreLocation == MySqlCertificateStoreLocation.None) { return(certs); } StoreLocation location = (_settings.CertificateStoreLocation == MySqlCertificateStoreLocation.CurrentUser) ? StoreLocation.CurrentUser : StoreLocation.LocalMachine; try { // Check for store-based certificate X509Store store = new X509Store(StoreName.My, location); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); if (_settings.CertificateThumbprint == null) { // Return all certificates from the store. certs.AddRange(store.Certificates); if (certs.Count == 0) { throw new MySqlException("No certificates were found in the certificate store"); } return(certs); } else { bool validateCert = _settings.SslMode == MySqlSslMode.VerifyCA || _settings.SslMode == MySqlSslMode.VerifyFull; // Find certificate with given thumbprint certs.AddRange(store.Certificates.Find(X509FindType.FindByThumbprint, _settings.CertificateThumbprint, validateCert)); if (certs.Count == 0) { throw new MySqlException(String.Format(Resources.InvalidCertificateThumbprint, _settings.CertificateThumbprint)); } return(certs); } } catch (CryptographicException ex) { throw new MySqlException("Certificate couldn't be loaded from the CertificateStoreLocation", ex); } }
public static void FindByValidThumbprint_RootCert() { using (X509Store machineRoot = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { machineRoot.Open(OpenFlags.ReadOnly); using (var watchedStoreCerts = new ImportedCollection(machineRoot.Certificates)) { X509Certificate2Collection storeCerts = watchedStoreCerts.Collection; X509Certificate2 rootCert = null; TimeSpan tolerance = TimeSpan.FromHours(12); // These APIs use local time, so use DateTime.Now, not DateTime.UtcNow. DateTime notBefore = DateTime.Now; DateTime notAfter = DateTime.Now.Subtract(tolerance); foreach (X509Certificate2 cert in storeCerts) { if (cert.NotBefore >= notBefore || cert.NotAfter <= notAfter) { // Not (safely) valid, skip. continue; } X509KeyUsageExtension keyUsageExtension = null; foreach (X509Extension extension in cert.Extensions) { keyUsageExtension = extension as X509KeyUsageExtension; if (keyUsageExtension != null) { break; } } // Some tool is putting the com.apple.systemdefault utility cert in the // LM\Root store on OSX machines; but it gets rejected by OpenSSL as an // invalid root for not having the Certificate Signing key usage value. // // While the real problem seems to be with whatever tool is putting it // in the bundle; we can work around it here. const X509KeyUsageFlags RequiredFlags = X509KeyUsageFlags.KeyCertSign; // No key usage extension means "good for all usages" if (keyUsageExtension != null && (keyUsageExtension.KeyUsages & RequiredFlags) != RequiredFlags) { // Not a valid KeyUsage, skip. continue; } using (ChainHolder chainHolder = new ChainHolder()) { chainHolder.Chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; if (!chainHolder.Chain.Build(cert)) { // Despite being not expired and having a valid KeyUsage, it's // not considered a valid root/chain. continue; } } rootCert = cert; break; } // Just in case someone has a system with no valid trusted root certs whatsoever. if (rootCert != null) { X509Certificate2Collection matches = storeCerts.Find(X509FindType.FindByThumbprint, rootCert.Thumbprint, true); using (new ImportedCollection(matches)) { // Improve the debuggability, since the root cert found on each // machine might be different if (matches.Count == 0) { Assert.True( false, $"Root certificate '{rootCert.Subject}' ({rootCert.NotBefore} - {rootCert.NotAfter}) is findable with thumbprint '{rootCert.Thumbprint}' and validOnly=true"); } Assert.NotSame(rootCert, matches[0]); Assert.Equal(rootCert, matches[0]); } } } } }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.Configure <ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; }); var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; var useSqlServer = Convert.ToBoolean(Configuration["BlazorBoilerplate:UseSqlServer"] ?? "false"); var dbConnString = useSqlServer ? Configuration.GetConnectionString("DefaultConnection") : $"Filename={Configuration.GetConnectionString("SqlLiteConnectionFileName")}"; var authAuthority = Configuration["BlazorBoilerplate:IS4ApplicationUrl"].TrimEnd('/'); void DbContextOptionsBuilder(DbContextOptionsBuilder builder) { if (useSqlServer) { builder.UseSqlServer(dbConnString, sql => sql.MigrationsAssembly(migrationsAssembly)); } else if (Convert.ToBoolean(Configuration["BlazorBoilerplate:UsePostgresServer"] ?? "false")) { builder.UseNpgsql(Configuration.GetConnectionString("PostgresConnection"), sql => sql.MigrationsAssembly(migrationsAssembly)); } else { builder.UseSqlite(dbConnString, sql => sql.MigrationsAssembly(migrationsAssembly)); } } services.AddDbContext <ApplicationDbContext>(DbContextOptionsBuilder); services.AddIdentity <ApplicationUser, IdentityRole <Guid> >() .AddRoles <IdentityRole <Guid> >() .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddScoped <IUserClaimsPrincipalFactory <ApplicationUser>, AdditionalUserClaimsPrincipalFactory>(); // Adds IdentityServer var identityServerBuilder = services.AddIdentityServer(options => { options.IssuerUri = authAuthority; options.Events.RaiseErrorEvents = true; options.Events.RaiseInformationEvents = true; options.Events.RaiseFailureEvents = true; options.Events.RaiseSuccessEvents = true; }) .AddConfigurationStore(options => { options.ConfigureDbContext = DbContextOptionsBuilder; }) .AddOperationalStore(options => { options.ConfigureDbContext = DbContextOptionsBuilder; // this enables automatic token cleanup. this is optional. options.EnableTokenCleanup = true; options.TokenCleanupInterval = 3600; //In Seconds 1 hour }) .AddAspNetIdentity <ApplicationUser>(); X509Certificate2 cert = null; if (_environment.IsDevelopment()) { // The AddDeveloperSigningCredential extension creates temporary key material for signing tokens. // This might be useful to get started, but needs to be replaced by some persistent key material for production scenarios. // See http://docs.identityserver.io/en/release/topics/crypto.html#refcrypto for more information. // https://stackoverflow.com/questions/42351274/identityserver4-hosting-in-iis //.AddDeveloperSigningCredential(true, @"C:\tempkey.rsa") identityServerBuilder.AddDeveloperSigningCredential(); } else { // running on azure // please make sure to replace your vault URI and your certificate name in appsettings.json! if (Convert.ToBoolean(Configuration["HostingOnAzure:RunsOnAzure"]) == true) { // if we use a key vault if (Convert.ToBoolean(Configuration["HostingOnAzure:AzurekeyVault:UsingKeyVault"]) == true) { // if managed app identity is used if (Convert.ToBoolean(Configuration["HostingOnAzure:AzurekeyVault:UseManagedAppIdentity"]) == true) { try { AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); var certificateBundle = keyVaultClient.GetSecretAsync(Configuration["HostingOnAzure:AzureKeyVault:VaultURI"], Configuration["HostingOnAzure:AzurekeyVault:CertificateName"]).GetAwaiter().GetResult(); var certificate = System.Convert.FromBase64String(certificateBundle.Value); cert = new X509Certificate2(certificate, (string)null, X509KeyStorageFlags.MachineKeySet); } catch (Exception ex) { throw (ex); } } // if app id and app secret are used if (Convert.ToBoolean(Configuration["HostingOnAzure:AzurekeyVault:UsingKeyVault"]) == false) { throw new NotImplementedException(); } } } // using local cert store if (Convert.ToBoolean(Configuration["BlazorBoilerplate:UseLocalCertStore"]) == true) { var certificateThumbprint = Configuration["BlazorBoilerplate:CertificateThumbprint"]; using (X509Store store = new X509Store("WebHosting", StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadOnly); var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false); if (certs.Count > 0) { cert = certs[0]; } else { // import PFX cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "AuthSample.pfx"), "Admin123", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); // save certificate and private key X509Store storeMy = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine); storeMy.Open(OpenFlags.ReadWrite); storeMy.Add(cert); } store.Close(); } } // pass the resulting certificate to Identity Server if (cert != null) { identityServerBuilder.AddSigningCredential(cert); } else { throw new FileNotFoundException("No certificate for Identity Server could be retrieved."); } } var authBuilder = services.AddAuthentication(options => { options.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; }) .AddIdentityServerAuthentication(options => { options.Authority = authAuthority; options.SupportedTokens = SupportedTokens.Jwt; options.RequireHttpsMetadata = _environment.IsProduction() ? true : false; options.ApiName = IdentityServerConfig.ApiName; }); //https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins?view=aspnetcore-3.1 if (Convert.ToBoolean(Configuration["ExternalAuthProviders:Google:Enabled"] ?? "false")) { authBuilder.AddGoogle(options => { options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme; options.ClientId = Configuration["ExternalAuthProviders:Google:ClientId"]; options.ClientSecret = Configuration["ExternalAuthProviders:Google:ClientSecret"]; }); } services.Configure <ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; }); //Add Policies / Claims / Authorization - https://stormpath.com/blog/tutorial-policy-based-authorization-asp-net-core services.AddAuthorization(options => { options.AddPolicy(Policies.IsAdmin, Policies.IsAdminPolicy()); options.AddPolicy(Policies.IsUser, Policies.IsUserPolicy()); options.AddPolicy(Policies.IsReadOnly, Policies.IsReadOnlyPolicy()); options.AddPolicy(Policies.IsMyDomain, Policies.IsMyDomainPolicy()); // valid only on serverside operations }); services.AddTransient <IAuthorizationHandler, DomainRequirementHandler>(); services.Configure <IdentityOptions>(options => { // Password settings options.Password.RequireDigit = false; options.Password.RequiredLength = 6; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; //options.Password.RequiredUniqueChars = 6; // Lockout settings options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); options.Lockout.MaxFailedAccessAttempts = 10; options.Lockout.AllowedForNewUsers = true; // Require Confirmed Email User settings if (Convert.ToBoolean(Configuration["BlazorBoilerplate:RequireConfirmedEmail"] ?? "false")) { options.User.RequireUniqueEmail = false; options.SignIn.RequireConfirmedEmail = true; } }); services.Configure <CookiePolicyOptions>(options => { options.MinimumSameSitePolicy = SameSiteMode.None; }); services.ConfigureExternalCookie(options => { // macOS login fix options.Cookie.SameSite = SameSiteMode.None; }); services.ConfigureApplicationCookie(options => { // macOS login fix options.Cookie.SameSite = SameSiteMode.None; options.Cookie.HttpOnly = false; // Suppress redirect on API URLs in ASP.NET Core -> https://stackoverflow.com/a/56384729/54159 options.Events = new CookieAuthenticationEvents() { OnRedirectToAccessDenied = context => { if (context.Request.Path.StartsWithSegments("/api")) { context.Response.StatusCode = (int)(HttpStatusCode.Unauthorized); } return(Task.CompletedTask); }, OnRedirectToLogin = context => { context.Response.StatusCode = 401; return(Task.CompletedTask); } }; }); services.AddControllers().AddNewtonsoftJson(); services.AddSignalR(); services.AddSwaggerDocument(config => { config.PostProcess = document => { document.Info.Version = "0.7.0"; document.Info.Title = "Blazor Boilerplate"; #if ServerSideBlazor #endif document.Info.Description = "Blazor Boilerplate / Starter Template using the Server Side Version"; #if ClientSideBlazor //document.Info.Description = "Blazor Boilerplate / Starter Template using the Client Side / Webassembly Version."; #endif }; }); services.AddResponseCompression(opts => { opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat( new[] { "application/octet-stream" }); }); services.AddScoped <IUserSession, UserSession>(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get <EmailConfiguration>()); services.AddTransient <IAccountService, AccountService>(); services.AddTransient <IEmailService, EmailService>(); services.AddTransient <IUserProfileService, UserProfileService>(); services.AddTransient <IApiLogService, ApiLogService>(); services.AddTransient <ITodoService, ToDoService>(); services.AddTransient <IMessageService, MessageService>(); services.AddTransient <ICategoryService, CategoryService>(); services.AddTransient <IOrderProductService, OrderProductService>(); // DB Creation and Seeding services.AddTransient <IDatabaseInitializer, DatabaseInitializer>(); //Automapper to map DTO to Models https://www.c-sharpcorner.com/UploadFile/1492b1/crud-operations-using-automapper-in-mvc-application/ var automapperConfig = new MapperConfiguration(configuration => { configuration.AddProfile(new MappingProfile()); }); var autoMapper = automapperConfig.CreateMapper(); services.AddSingleton(autoMapper); //#if ServerSideBlazor services.AddScoped <IAuthorizeApi, AuthorizeApi>(); services.AddScoped <IUserProfileApi, UserProfileApi>(); services.AddScoped <AppState>(); services.AddMatToaster(config => { config.Position = MatToastPosition.BottomRight; config.PreventDuplicates = true; config.NewestOnTop = true; config.ShowCloseButton = true; config.MaximumOpacity = 95; config.VisibleStateDuration = 3000; }); // Setup HttpClient for server side services.AddScoped <HttpClient>(); services.AddRazorPages(); services.AddServerSideBlazor(); // Authentication providers Log.Logger.Debug("Removing AuthenticationStateProvider..."); var serviceDescriptor = services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(AuthenticationStateProvider)); if (serviceDescriptor != null) { services.Remove(serviceDescriptor); } Log.Logger.Debug("Adding AuthenticationStateProvider..."); services.AddScoped <AuthenticationStateProvider, IdentityAuthenticationStateProvider>(); //#endif Log.Logger.Debug($"Total Services Registered: {services.Count}"); foreach (var service in services) { Log.Logger.Debug($"\n Service: {service.ServiceType.FullName}\n Lifetime: {service.Lifetime}\n Instance: {service.ImplementationType?.FullName}"); } }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = Authority, PostLogoutRedirectUri = postLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications() { // // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. // AuthorizationCodeReceived = async(context) => { var code = context.Code; if (certName.Length != 0) { // Create a Client Credential Using a Certificate // // Initialize the Certificate Credential to be used by ADAL. // First find the matching certificate in the cert store. // X509Certificate2 cert = null; X509Store store = new X509Store(StoreLocation.CurrentUser); try { store.Open(OpenFlags.ReadOnly); // Place all certificates in an X509Certificate2Collection object. X509Certificate2Collection certCollection = store.Certificates; // Find unexpired certificates. X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false); // From the collection of unexpired certificates, find the ones with the correct name. X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false); if (signingCert.Count == 0) { // No matching certificate found. return; } // Return the first certificate in the collection, has the right name and is current. cert = signingCert[0]; } finally { store.Close(); } // Then create the certificate credential. ClientAssertionCertificate credential = new ClientAssertionCertificate(clientId, cert); string userObjectID = context.AuthenticationTicket.Identity.FindFirst( "http://schemas.microsoft.com/identity/claims/objectidentifier").Value; AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID)); AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId); AuthenticationHelper.token = result.AccessToken; } else { // Create a Client Credential Using an Application Key ClientCredential credential = new ClientCredential(clientId, appKey); string userObjectID = context.AuthenticationTicket.Identity.FindFirst( "http://schemas.microsoft.com/identity/claims/objectidentifier").Value; AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID)); AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId); AuthenticationHelper.token = result.AccessToken; } } } }); }
private static X509Certificate2Collection findCertificates(string prop, StoreLocation storeLocation, string name, string value) { // // Open the X509 certificate store. // X509Store store = null; try { try { store = new X509Store((StoreName)Enum.Parse(typeof(StoreName), name, true), storeLocation); } catch (ArgumentException) { store = new X509Store(name, storeLocation); } store.Open(OpenFlags.ReadOnly); } catch (Exception ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); e.reason = "IceSSL: failure while opening store specified by " + prop; throw e; } // // Start with all of the certificates in the collection and filter as necessary. // // - If the value is "*", return all certificates. // - Otherwise, search using key:value pairs. The following keys are supported: // // Issuer // IssuerDN // Serial // Subject // SubjectDN // SubjectKeyId // Thumbprint // // A value must be enclosed in single or double quotes if it contains whitespace. // X509Certificate2Collection result = new X509Certificate2Collection(); result.AddRange(store.Certificates); try { if (value != "*") { if (value.IndexOf(':') == -1) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: no key in `" + value + "'"; throw e; } int start = 0; int pos; while ((pos = value.IndexOf(':', start)) != -1) { // // Parse the X509FindType. // string field = value.Substring(start, pos - start).Trim().ToUpperInvariant(); X509FindType findType; if (field.Equals("SUBJECT")) { findType = X509FindType.FindBySubjectName; } else if (field.Equals("SUBJECTDN")) { findType = X509FindType.FindBySubjectDistinguishedName; } else if (field.Equals("ISSUER")) { findType = X509FindType.FindByIssuerName; } else if (field.Equals("ISSUERDN")) { findType = X509FindType.FindByIssuerDistinguishedName; } else if (field.Equals("THUMBPRINT")) { findType = X509FindType.FindByThumbprint; } else if (field.Equals("SUBJECTKEYID")) { findType = X509FindType.FindBySubjectKeyIdentifier; } else if (field.Equals("SERIAL")) { findType = X509FindType.FindBySerialNumber; } else { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unknown key in `" + value + "'"; throw e; } // // Parse the argument. // start = pos + 1; while (start < value.Length && (value[start] == ' ' || value[start] == '\t')) { ++start; } if (start == value.Length) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: missing argument in `" + value + "'"; throw e; } string arg; if (value[start] == '"' || value[start] == '\'') { int end = start; ++end; while (end < value.Length) { if (value[end] == value[start] && value[end - 1] != '\\') { break; } ++end; } if (end == value.Length || value[end] != value[start]) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); e.reason = "IceSSL: unmatched quote in `" + value + "'"; throw e; } ++start; arg = value.Substring(start, end - start); start = end + 1; } else { char[] ws = new char[] { ' ', '\t' }; int end = value.IndexOfAny(ws, start); if (end == -1) { arg = value.Substring(start); start = value.Length; } else { arg = value.Substring(start, end - start); start = end + 1; } } // // Execute the query. // // TODO: allow user to specify a value for validOnly? // bool validOnly = false; if (findType == X509FindType.FindBySubjectDistinguishedName || findType == X509FindType.FindByIssuerDistinguishedName) { X500DistinguishedNameFlags[] flags = { X500DistinguishedNameFlags.None, X500DistinguishedNameFlags.Reversed, }; X500DistinguishedName dn = new X500DistinguishedName(arg); X509Certificate2Collection r = result; for (int i = 0; i < flags.Length; ++i) { r = result.Find(findType, dn.Decode(flags[i]), validOnly); if (r.Count > 0) { break; } } result = r; } else { result = result.Find(findType, arg, validOnly); } } } } finally { store.Close(); } return(result); }
public static X509Certificate2 CertificateFromThumbprint(X509Store store, string thumbprint, bool validOnly) { X509Certificate2Collection foundCertificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly); return(foundCertificates.Count == 0 ? null : foundCertificates[0]); }
/// <summary> /// Unlike X509Store.Remove() this function also cleans up private-keys /// </summary> public static void RemoveCertificateFromStore(string thumbprint, StoreLocation storeLocation, string storeName) { using (AcquireSemaphore()) { var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); var found = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (found.Count == 0) { return; } var certificate = found[0]; var certificateHandle = new SafeCertContextHandle(found[0].Handle, false); // If the certificate has a private-key, remove it if (certificateHandle.HasPrivateKey()) { var keyProvInfo = certificateHandle.GetCertificateProperty <KeyProviderInfo>(CertificateProperty.KeyProviderInfo); // If it is a CNG key if (keyProvInfo.dwProvType == 0) { try { var key = CertificatePal.GetCngPrivateKey(certificateHandle); CertificatePal.DeleteCngKey(key); } catch (Exception ex) { throw new Exception("Exception while deleting CNG private key", ex); } } else // CAPI key { try { IntPtr providerHandle; var acquireContextFlags = CryptAcquireContextFlags.Delete | CryptAcquireContextFlags.Silent; if (storeLocation == StoreLocation.LocalMachine) { acquireContextFlags = acquireContextFlags | CryptAcquireContextFlags.MachineKeySet; } var success = Native.CryptAcquireContext(out providerHandle, keyProvInfo.pwszContainerName, keyProvInfo.pwszProvName, keyProvInfo.dwProvType, acquireContextFlags); if (!success) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } catch (Exception ex) { // Swallow keyset does not exist if (!(ex is CryptographicException && ex.Message.Contains("Keyset does not exist"))) { throw new Exception("Exception while deleting CAPI private key", ex); } } } } store.Remove(certificate); store.Close(); } }
public static X509Certificate2 GetCertificate(StoreName name, StoreLocation location, string subjectName, DateTime?validOn, bool selectMaximumValidityOnMultipleFound, bool publicKeyOnly, out CertificateRetrievalStatus status) { status = CertificateRetrievalStatus.NotFound; if (string.IsNullOrEmpty(subjectName)) { return(null); } var clockSkew = TimeSpan.FromMinutes(5); if (selectMaximumValidityOnMultipleFound && !validOn.HasValue) { throw new ArgumentException($"{nameof(selectMaximumValidityOnMultipleFound)} without {nameof(validOn)} specified", nameof(selectMaximumValidityOnMultipleFound)); } X509Store store = new X509Store(name, location); X509Certificate2Collection certificates = null; store.Open(OpenFlags.ReadOnly); try { X509Certificate2 result = null; // note: X509Store.Certificates property created a new collection certificates = store.Certificates; for (int i = 0; i < certificates.Count; i++) { X509Certificate2 cert = certificates[i]; if (string.Equals(cert.SubjectName.Name, subjectName, StringComparison.Ordinal)) { if (validOn.HasValue) { if (CommonUtility.IsDateTimeInRange(cert.NotBefore, cert.NotAfter, validOn.Value, clockSkew, clockSkew) != DateTimeRangeValidity.Valid) { continue; } } if (result != null) { if (selectMaximumValidityOnMultipleFound) { if (cert.NotAfter > result.NotAfter) { if (publicKeyOnly) { result = new X509Certificate2(cert.RawData); } else { result = new X509Certificate2(cert); } } continue; } status = CertificateRetrievalStatus.MultipleFound; return(null); } if (publicKeyOnly) { result = new X509Certificate2(cert.RawData); } else { result = new X509Certificate2(cert); } } } if (result == null) { status = CertificateRetrievalStatus.NotFound; return(null); } status = CertificateRetrievalStatus.None; return(result); } finally { if (certificates != null) { for (int i = 0; i < certificates.Count; i++) { X509Certificate2 cert = certificates[i]; cert.Reset(); } } store.Close(); } }
public IList <X509Certificate2> ListCertificates( StoreName storeName, StoreLocation location, bool isValid, bool requireExportable = true) { Log.ListCertificatesStart(location, storeName); var certificates = new List <X509Certificate2>(); try { using var store = new X509Store(storeName, location); store.Open(OpenFlags.ReadOnly); certificates.AddRange(store.Certificates.OfType <X509Certificate2>()); IEnumerable <X509Certificate2> matchingCertificates = certificates; matchingCertificates = matchingCertificates .Where(c => HasOid(c, AspNetHttpsOid)); if (Log.IsEnabled()) { Log.DescribeFoundCertificates(ToCertificateDescription(matchingCertificates)); } if (isValid) { // Ensure the certificate hasn't expired, has a private key and its exportable // (for container/unix scenarios). Log.CheckCertificatesValidity(); var now = DateTimeOffset.Now; var validCertificates = matchingCertificates .Where(c => IsValidCertificate(c, now, requireExportable)) .OrderByDescending(c => GetCertificateVersion(c)) .ToArray(); if (Log.IsEnabled()) { var invalidCertificates = matchingCertificates.Except(validCertificates); Log.DescribeValidCertificates(ToCertificateDescription(validCertificates)); Log.DescribeInvalidValidCertificates(ToCertificateDescription(invalidCertificates)); } matchingCertificates = validCertificates; } // We need to enumerate the certificates early to prevent disposing issues. matchingCertificates = matchingCertificates.ToList(); var certificatesToDispose = certificates.Except(matchingCertificates); DisposeCertificates(certificatesToDispose); store.Close(); Log.ListCertificatesEnd(); return((IList <X509Certificate2>)matchingCertificates); } catch (Exception e) { if (Log.IsEnabled()) { Log.ListCertificatesError(e.ToString()); } DisposeCertificates(certificates); certificates.Clear(); return(certificates); } bool HasOid(X509Certificate2 certificate, string oid) => certificate.Extensions.OfType <X509Extension>() .Any(e => string.Equals(oid, e.Oid?.Value, StringComparison.Ordinal));
private void InitializeServerContext( X509Certificate serverCertificate, bool clientCertificateRequired, X509Chain caCerts, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocation) { if (serverCertificate == null) { throw new ArgumentNullException("serverCertificate", "Server certificate cannot be null"); } if (!serverCertificate.HasPrivateKey) { throw new ArgumentException("Server certificate must have a private key", "serverCertificate"); } // Initialize the context sslContext = new SslContext(SslMethod.SSLv23_server_method); // Remove support for protocols not specified in the enabledSslProtocols if ((enabledSslProtocols & SslProtocols.Ssl2) != SslProtocols.Ssl2) { sslContext.Options |= SslOptions.SSL_OP_NO_SSLv2; } if ((enabledSslProtocols & SslProtocols.Ssl3) != SslProtocols.Ssl3 && ((enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default)) { // no SSLv3 support sslContext.Options |= SslOptions.SSL_OP_NO_SSLv3; } if ((enabledSslProtocols & SslProtocols.Tls) != SslProtocols.Tls && (enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default) { sslContext.Options |= SslOptions.SSL_OP_NO_TLSv1; } /* // Initialize the context with the specified ssl version switch (enabledSslProtocols) { case SslProtocols.None: throw new ArgumentException("SslProtocol.None is not supported", "enabledSslProtocols"); break; case SslProtocols.Ssl2: sslContext = new SslContext(SslMethod.SSLv2_server_method); break; case SslProtocols.Ssl3: case SslProtocols.Default: sslContext = new SslContext(SslMethod.SSLv3_server_method); break; case SslProtocols.Tls: sslContext = new SslContext(SslMethod.TLSv1_server_method); break; } */ // Set the context mode sslContext.Mode = SslMode.SSL_MODE_AUTO_RETRY; // Set the workaround options sslContext.Options = SslOptions.SSL_OP_ALL; // Set the client certificate verification callback if we are requiring client certs if (clientCertificateRequired) { sslContext.SetVerify(VerifyMode.SSL_VERIFY_PEER | VerifyMode.SSL_VERIFY_FAIL_IF_NO_PEER_CERT, remoteCertificateSelectionCallback); } else { sslContext.SetVerify(VerifyMode.SSL_VERIFY_NONE, null); } // Set the client certificate max verification depth sslContext.SetVerifyDepth(10); // Set the certificate store and ca list if (caCerts != null) { // Don't take ownership of the X509Store IntPtr. When we // SetCertificateStore, the context takes ownership of the store pointer. X509Store cert_store = new X509Store(caCerts, false); sslContext.SetCertificateStore(cert_store); Core.Stack<X509Name> name_stack = new Core.Stack<X509Name>(); foreach (X509Certificate cert in caCerts) { X509Name subject = cert.Subject; name_stack.Add(subject); } // Assign the stack to the context sslContext.CAList = name_stack; } // Set the cipher string sslContext.SetCipherList(GetCipherString(false, enabledSslProtocols, sslStrength)); // Set the certificate sslContext.UseCertificate(serverCertificate); // Set the private key sslContext.UsePrivateKey(serverCertificate.PrivateKey); // Set the session id context sslContext.SetSessionIdContext(Encoding.ASCII.GetBytes(AppDomain.CurrentDomain.FriendlyName)); }
/// <summary> /// Finds all valid installed certificates /// </summary> public static void FindCertificates() { if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) { // run certtool y to get the currently installed certificates CertToolData = ""; Process CertTool = new Process(); CertTool.StartInfo.FileName = "/usr/bin/security"; CertTool.StartInfo.UseShellExecute = false; CertTool.StartInfo.Arguments = "find-certificate -a -c \"iPhone\" -p"; CertTool.StartInfo.RedirectStandardOutput = true; CertTool.OutputDataReceived += new DataReceivedEventHandler(OutputReceivedCertToolProcessCall); CertTool.Start(); CertTool.BeginOutputReadLine(); CertTool.WaitForExit(); if (CertTool.ExitCode == 0) { string header = "-----BEGIN CERTIFICATE-----\n"; string footer = "-----END CERTIFICATE-----"; int start = CertToolData.IndexOf(header); while (start != -1) { start += header.Length; int end = CertToolData.IndexOf(footer, start); string base64 = CertToolData.Substring(start, (end - start)); byte[] certData = Convert.FromBase64String(base64); X509Certificate2 cert = new X509Certificate2(certData); DateTime EffectiveDate = cert.NotBefore; DateTime ExpirationDate = cert.NotAfter; DateTime Now = DateTime.UtcNow; string Subject = cert.Subject; int SubjStart = Subject.IndexOf("CN=") + 3; int SubjEnd = Subject.IndexOf(",", SubjStart); cert.FriendlyName = Subject.Substring(SubjStart, (SubjEnd - SubjStart)); bool bCertTimeIsValid = (EffectiveDate < Now) && (ExpirationDate > Now); Program.LogVerbose("CERTIFICATE-Name:{0},Validity:{1},StartDate:{2},EndDate:{3}", cert.FriendlyName, bCertTimeIsValid ? "VALID" : "EXPIRED", EffectiveDate.ToString("o"), ExpirationDate.ToString("o")); start = CertToolData.IndexOf(header, start); } } } else { // Open the personal certificate store on this machine X509Store Store = new X509Store(); Store.Open(OpenFlags.ReadOnly); // Try finding all certificates that match either iPhone Developer or iPhone Distribution X509Certificate2Collection FoundCerts = Store.Certificates.Find(X509FindType.FindBySubjectName, "iPhone Developer", false); foreach (X509Certificate2 TestCert in FoundCerts) { DateTime EffectiveDate = TestCert.NotBefore; DateTime ExpirationDate = TestCert.NotAfter; DateTime Now = DateTime.Now; bool bCertTimeIsValid = (EffectiveDate < Now) && (ExpirationDate > Now); Program.LogVerbose("CERTIFICATE-Name:{0},Validity:{1},StartDate:{2},EndDate:{3}", TestCert.FriendlyName, bCertTimeIsValid ? "VALID" : "EXPIRED", EffectiveDate.ToString("o"), ExpirationDate.ToString("o")); } FoundCerts = Store.Certificates.Find(X509FindType.FindBySubjectName, "iPhone Distribution", false); foreach (X509Certificate2 TestCert in FoundCerts) { DateTime EffectiveDate = TestCert.NotBefore; DateTime ExpirationDate = TestCert.NotAfter; DateTime Now = DateTime.Now; bool bCertTimeIsValid = (EffectiveDate < Now) && (ExpirationDate > Now); Program.LogVerbose("CERTIFICATE-Name:{0},Validity:{1},StartDate:{2},EndDate:{3}", TestCert.FriendlyName, bCertTimeIsValid ? "VALID" : "EXPIRED", EffectiveDate.ToString("o"), ExpirationDate.ToString("o")); } Store.Close(); } }
public new SSLCertificate InstallPfx(byte[] certificate, string password, WebSite website) { SSLCertificate newcert = null, oldcert = null; // Ensure we perform operations safely and preserve the original state during all manipulations, save the oldcert if one is used if (CheckCertificate(website)) { oldcert = GetCurrentSiteCertificate(website); } X509Certificate2 x509Cert; var store = new X509Store(CertificateStoreName, StoreLocation.LocalMachine); if (UseCCS) { // We need to use this constructor or we won't be able to export this certificate x509Cert = new X509Certificate2(certificate, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); var certData = x509Cert.Export(X509ContentType.Pfx); var convertedCert = new X509Certificate2(certData, string.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); // Attempts to move certificate to CCS UNC path try { // Create a stream out of that new certificate certData = convertedCert.Export(X509ContentType.Pfx, CCSCommonPassword); // Open UNC path and set path to certificate subject var filename = (CCSUncPath.EndsWith("/") ? CCSUncPath: CCSUncPath + "/") + x509Cert.GetNameInfo(X509NameType.SimpleName, false) + ".pfx"; var writer = new BinaryWriter(File.Open(filename, FileMode.Create)); writer.Write(certData); writer.Flush(); writer.Close(); // Certificate saved } catch (Exception ex) { // Log error Log.WriteError("SSLModuleService could not save certificate to Centralized Certificate Store", ex); // Re-throw throw; } } else { x509Cert = new X509Certificate2(certificate, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); // Step 1: Register X.509 certificate in the store // Trying to keep X.509 store open as less as possible try { store.Open(OpenFlags.ReadWrite); store.Add(x509Cert); } catch (Exception ex) { Log.WriteError(String.Format("SSLModuleService could not import PFX into X509Store('{0}', '{1}')", store.Name, store.Location), ex); // Re-throw error throw; } finally { store.Close(); } } // Step 2: Instantiate a copy of new X.509 certificate try { newcert = GetSSLCertificateFromX509Certificate2(x509Cert); } catch (Exception ex) { HandleExceptionAndRollbackCertificate(store, x509Cert, null, website, "SSLModuleService could not instantiate a copy of new X.509 certificate.", ex); } // Step 3: Remove old certificate from the web site if any try { // Check if certificate already exists, remove it. if (oldcert != null) { DeleteCertificate(oldcert, website); } } catch (Exception ex) { HandleExceptionAndRollbackCertificate(store, x509Cert, null, website, string.Format("SSLModuleService could not remove existing certificate from '{0}' web site.", website.Name), ex); } // Step 4: Register new certificate with HTTPS binding on the web site try { AddBinding(x509Cert, website); } catch (Exception ex) { HandleExceptionAndRollbackCertificate(store, x509Cert, oldcert, website, String.Format("SSLModuleService could not add new X.509 certificate to '{0}' web site.", website.Name), ex); } return(newcert); }
public static void X509Cert2ToStringVerbose() { X509Store store = new X509Store("My", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); foreach (X509Certificate2 c in store.Certificates) { Assert.False(string.IsNullOrWhiteSpace(c.ToString(true))); } }
/// <summary> /// Tries to find a matching certificate on this machine from the the serial number of one of the /// certificates in the mobile provision (the one in the mobileprovision is missing the public/private key pair) /// </summary> public static X509Certificate2 FindCertificate(MobileProvision ProvisionToWorkFrom) { Program.LogVerbose(" Looking for a certificate that matches the application identifier '{0}'", ProvisionToWorkFrom.ApplicationIdentifier); X509Certificate2 Result = null; if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) { // run certtool y to get the currently installed certificates CertToolData = ""; Process CertTool = new Process(); CertTool.StartInfo.FileName = "/usr/bin/security"; CertTool.StartInfo.UseShellExecute = false; CertTool.StartInfo.Arguments = "find-identity -p codesigning -v"; CertTool.StartInfo.RedirectStandardOutput = true; CertTool.OutputDataReceived += new DataReceivedEventHandler(OutputReceivedCertToolProcessCall); CertTool.Start(); CertTool.BeginOutputReadLine(); CertTool.WaitForExit(); if (CertTool.ExitCode == 0) { foreach (X509Certificate2 SourceCert in ProvisionToWorkFrom.DeveloperCertificates) { X509Certificate2 ValidInTimeCert = null; // see if certificate can be found by serial number string CertHash = SourceCert.GetCertHashString(); if (CertToolData.Contains(CertHash)) { ValidInTimeCert = SourceCert; } if (ValidInTimeCert != null) { int StartIndex = SourceCert.SubjectName.Name.IndexOf("CN=") + 3; int EndIndex = SourceCert.SubjectName.Name.IndexOf(", ", StartIndex); SourceCert.FriendlyName = SourceCert.SubjectName.Name.Substring(StartIndex, EndIndex - StartIndex); // Found a cert in the valid time range, quit now! Result = ValidInTimeCert; break; } } } } else { // Open the personal certificate store on this machine X509Store Store = new X509Store(); Store.Open(OpenFlags.ReadOnly); // Try finding a matching certificate from the serial number (the one in the mobileprovision is missing the public/private key pair) foreach (X509Certificate2 SourceCert in ProvisionToWorkFrom.DeveloperCertificates) { X509Certificate2Collection FoundCerts = Store.Certificates.Find(X509FindType.FindBySerialNumber, SourceCert.SerialNumber, false); Program.LogVerbose(" .. Provision entry SN '{0}' matched {1} installed certificate(s)", SourceCert.SerialNumber, FoundCerts.Count); X509Certificate2 ValidInTimeCert = null; foreach (X509Certificate2 TestCert in FoundCerts) { //@TODO: Pretty sure the certificate information from the library is in local time, not UTC and this works as expected, but it should be verified! DateTime EffectiveDate = TestCert.NotBefore; DateTime ExpirationDate = TestCert.NotAfter; DateTime Now = DateTime.Now; bool bCertTimeIsValid = (EffectiveDate < Now) && (ExpirationDate > Now); Program.LogVerbose(" .. .. Installed certificate '{0}' is {1} (range '{2}' to '{3}')", TestCert.FriendlyName, bCertTimeIsValid ? "valid (choosing it)" : "EXPIRED", TestCert.GetEffectiveDateString(), TestCert.GetExpirationDateString()); if (bCertTimeIsValid) { ValidInTimeCert = TestCert; break; } } if (ValidInTimeCert != null) { // Found a cert in the valid time range, quit now! Result = ValidInTimeCert; break; } } Store.Close(); } if (Result == null) { Program.LogVerbose(" .. Failed to find a valid certificate that was in date"); } return(Result); }