// This should only be called from config public void SetupCertificate(string caCert, string clientCert, string clientCertPrivateKey, string clientCertArchive, string clientCertPassword) { Trace.Info("Setup agent certificate setting base on configuration inputs."); if (!string.IsNullOrEmpty(caCert)) { ArgUtil.File(caCert, nameof(caCert)); Trace.Info($"Self-Signed CA '{caCert}'"); } if (!string.IsNullOrEmpty(clientCert)) { ArgUtil.File(clientCert, nameof(clientCert)); ArgUtil.File(clientCertPrivateKey, nameof(clientCertPrivateKey)); ArgUtil.File(clientCertArchive, nameof(clientCertArchive)); Trace.Info($"Client cert '{clientCert}'"); Trace.Info($"Client cert private key '{clientCertPrivateKey}'"); Trace.Info($"Client cert archive '{clientCertArchive}'"); } // TODO: Setup ServicePointManager.ServerCertificateValidationCallback when adopt netcore 2.0 to support self-signed cert for agent infrastructure. CACertificateFile = caCert; ClientCertificateFile = clientCert; ClientCertificatePrivateKeyFile = clientCertPrivateKey; ClientCertificateArchiveFile = clientCertArchive; ClientCertificatePassword = clientCertPassword; _clientCertificates.Clear(); if (!string.IsNullOrEmpty(ClientCertificateArchiveFile)) { _clientCertificates.Add(new X509Certificate2(ClientCertificateArchiveFile, ClientCertificatePassword)); } }
/////////////////////////////////////////////////////////////////////// /// /// <summary> /// Carry out the filters requested. /// </summary> /// static X509Certificate2 FilterCertificates(X509Certificate2Collection certificates) { int index; if (0 < certificates.Count && null != sha1) { certificates = certificates.Find(X509FindType.FindByThumbprint, sha1, false); } if (0 < certificates.Count && 0 < subjects.Count) { foreach (string subject in subjects) { certificates = certificates.Find(X509FindType.FindBySubjectDistinguishedName, subject, false); } } if (0 < certificates.Count && 0 < issuers.Count) { foreach (string issuer in issuers) { certificates = certificates.Find(X509FindType.FindByIssuerDistinguishedName, issuer, false); } } // filter out certificates without a private key. if (0 < certificates.Count) { X509Certificate2Collection collection = new X509Certificate2Collection(); for (index = 0; index < certificates.Count; index++) { try { if (certificates[index].PrivateKey != null) { collection.Add(certificates[index]); } } catch {} } certificates.Clear(); certificates = collection; } // finally, ask the user to select a certificate if more than one is found. if (1 < certificates.Count) { certificates = X509Certificate2UI.SelectFromCollection(certificates, "Certificates", "Please select a certificate", X509SelectionFlag.SingleSelection); } if (certificates.Count != 1) { throw new InternalException("Internal error: No valid certificates were found to sign the document."); } return(certificates.Count == 0 ? null : certificates[0]); }
private static void ResetAll(X509Certificate2Collection certs) { if (certs != null && certs.Count > 0) { for (int i = 0; i < certs.Count; i++) { certs[i].Reset(); } certs.Clear(); } }
// This should only be called from config public void SetupCertificate(bool skipCertValidation, string caCert, string clientCert, string clientCertPrivateKey, string clientCertArchive, string clientCertPassword) { Trace.Info("Setup agent certificate setting base on configuration inputs."); if (skipCertValidation) { Trace.Info("Ignore SSL server certificate validation error"); SkipServerCertificateValidation = true; VssClientHttpRequestSettings.Default.ServerCertificateValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; } if (!string.IsNullOrEmpty(caCert)) { ArgUtil.File(caCert, nameof(caCert)); Trace.Info($"Self-Signed CA '{caCert}'"); } if (!string.IsNullOrEmpty(clientCert)) { ArgUtil.File(clientCert, nameof(clientCert)); ArgUtil.File(clientCertPrivateKey, nameof(clientCertPrivateKey)); ArgUtil.File(clientCertArchive, nameof(clientCertArchive)); Trace.Info($"Client cert '{clientCert}'"); Trace.Info($"Client cert private key '{clientCertPrivateKey}'"); Trace.Info($"Client cert archive '{clientCertArchive}'"); } CACertificateFile = caCert; ClientCertificateFile = clientCert; ClientCertificatePrivateKeyFile = clientCertPrivateKey; ClientCertificateArchiveFile = clientCertArchive; ClientCertificatePassword = clientCertPassword; _clientCertificates.Clear(); if (!string.IsNullOrEmpty(ClientCertificateArchiveFile)) { _clientCertificates.Add(new X509Certificate2(ClientCertificateArchiveFile, ClientCertificatePassword)); } }
public void SelfSignedTest() { var chain = new X509Chain(); var trusted = new X509Certificate2Collection(); Assert.IsFalse(chain.Build(Certificates.SelfSigned)); Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SelfSigned, trusted)); trusted.Add(Certificates.SelfSigned); Assert.IsTrue(chain.VerifyWithExtraRoots(Certificates.SelfSigned, trusted)); Assert.IsFalse(chain.Build(Certificates.SelfSigned)); trusted.Clear(); Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SelfSigned, trusted)); Assert.IsFalse(chain.Build(Certificates.SelfSigned)); }
/// <summary> /// Adds certificates to this store from a folder. /// </summary> /// <param name="folderPath">The path to a folder containing certificate files</param> /// <param name="flags">The <see cref="X509KeyStorageFlags"/> for the keyfile</param> public void ImportFolder(string folderPath, X509KeyStorageFlags flags) { string[] files = System.IO.Directory.GetFiles(folderPath); if (files.IsNullOrEmpty()) { return; } X509Certificate2Collection certs = new X509Certificate2Collection(); foreach (string filePath in files) { certs.Clear(); certs.Import(filePath, null, flags); this.Add(certs); } }
public void SelfSignedRootTest() { var chain = new X509Chain(); var trusted = new X509Certificate2Collection(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; Assert.IsFalse(chain.Build(Certificates.SignedBySelfSigned)); Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SignedBySelfSigned, trusted)); trusted.Add(Certificates.SelfSigned); Assert.IsTrue(chain.VerifyWithExtraRoots(Certificates.SignedBySelfSigned, trusted)); Assert.IsFalse(chain.Build(Certificates.SignedBySelfSigned)); trusted.Clear(); Assert.IsFalse(chain.VerifyWithExtraRoots(Certificates.SignedBySelfSigned, trusted)); Assert.IsFalse(chain.Build(Certificates.SignedBySelfSigned)); }
private void SetCertSet() { if (!cbJustOne.Checked) { lbCerts.SelectedIndex = -1; } certsToAuthWith.Clear(); if (cbJustOne.Checked && lbCerts.SelectedIndex > 0) { certsToAuthWith.Add(collection[lbCerts.SelectedIndex - 1]); txtResponse.Text += $"\r\n{certsToAuthWith[0].SubjectName.Name} selected"; } else { certsToAuthWith.AddRange(collection); } txtResponse.Text += $"\r\nAuthenticating with {certsToAuthWith.Count} cert(s)"; }
// // Certificate support routines // // Given a list of certs (expressed as byte[]s), loads them into // the certificate collection private void LoadCertificateCollection(List <byte[]> certificatesToLoad) { // To support reload _certificates.Clear(); Debug.Assert(_certificates.Count == 0); GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "LoadCertificateCollection: loading {0} certs", certificatesToLoad.Count); foreach (byte[] rawCert in certificatesToLoad) { try { _certificates.Import(rawCert); } catch (System.Security.Cryptography.CryptographicException) { // skip the invalid certificate GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthenticablePrincipal", "LoadCertificateCollection: skipped bad cert"); continue; } } }
protected static bool TryImportFromPemFile(string filePath, out X509Certificate2Collection certificates) { certificates = new X509Certificate2Collection(); try { certificates.ImportFromPemFile(filePath); return(true); } catch (Exception ex) when ( ex is CryptographicException || ex is FileNotFoundException || ex is DirectoryNotFoundException ) { certificates.Clear(); } return(false); }
public static void TestCertificateRetrieval() { // retrieve the winfab certs with SubjectName matching var testCerts = RetrieveTestCerts(StoreNamePersonal, StoreLocationLM, CNPrefix); // inventory them to ensure we have certs for all test scenarios var testCertCatalog = InventoryTestCerts(testCerts, out string duplicateCN, out string expiredCN, out string expiredTP); // start running the tests // 1. ensure we get an exact match Console.WriteLine("\n** running test case 1"); // pick a CN which has a single match string expectedCN = String.Empty; X509Certificate2 expectedCert = null; foreach (var kvp in testCertCatalog) { if (kvp.Value.Count > 1) { continue; } expectedCN = kvp.Key; expectedCert = kvp.Value[0]; break; } if (String.IsNullOrWhiteSpace(expectedCN)) { // highly unlikely, but all have duplicates // pick a cn at random, and pick a non-expired cert with that cn var targetIdx = new Random((int)DateTime.UtcNow.Ticks).Next(testCertCatalog.Count - 1); var idx = 0; // grr; no index-based access foreach (var certKvp in testCertCatalog) { if (idx++ != targetIdx) { continue; } expectedCN = certKvp.Key; foreach (var cert in certKvp.Value) { if (!cert.Thumbprint.Equals(expiredTP)) { expectedCert = certKvp.Value[0]; break; } } break; } } X509Certificate2Collection retrievedCerts = new X509Certificate2Collection(); // saves the null checks try { retrievedCerts = FindMatchingCertificates(StoreNamePersonal, StoreLocationLM, X509FindType.FindBySubjectName.ToString(), expectedCN, String.Empty, doTakeMostRecentOnly: true); } catch (Exception ex) { Console.WriteLine("Caught exception: {0}: {1}", ex.HResult, ex.Message); } if (retrievedCerts.Count < 1) { Console.WriteLine("FAIL: did not retrieve existing match for CN='{0}'", expectedCN); } if (retrievedCerts.Count > 1) { Console.WriteLine("FAIL: retrieved multiple matches for CN='{0}'", expectedCN); } if (!VerifyCertsAreEqual(retrievedCerts[0], expectedCert)) { Console.WriteLine("FAIL: the cert retrieved by CN='{0}' (tp: {1}) does not match the expected one (tp: {2})", expectedCN, retrievedCerts[0].Thumbprint, expectedCert.Thumbprint); } // 2. ensure we don't get partial matches Console.WriteLine("\n** running test case 2"); retrievedCerts.Clear(); try { retrievedCerts = FindMatchingCertificates(StoreNamePersonal, StoreLocationLM, X509FindType.FindBySubjectName.ToString(), CNPrefix, String.Empty, doTakeMostRecentOnly: true); } catch (Exception ex) { Console.WriteLine("Caught exception: {0}: {1}", ex.HResult, ex.Message); } if (retrievedCerts.Count > 0) { Console.WriteLine("FAIL: retrieved matches for partial CN='{0}'", CNPrefix); } // 3. ensure we don't get expired certs Console.WriteLine("\n** running test case 3"); retrievedCerts.Clear(); try { retrievedCerts = FindMatchingCertificates(StoreNamePersonal, StoreLocationLM, X509FindType.FindBySubjectName.ToString(), expiredCN, String.Empty, doTakeMostRecentOnly: true); } catch (Exception ex) { Console.WriteLine("Caught exception: {0}: {1}", ex.HResult, ex.Message); } bool shouldHaveFoundMatches = testCertCatalog[expiredCN].Count > 1; if (shouldHaveFoundMatches) { if (retrievedCerts.Count < 1) { Console.WriteLine("FAIL: did not retrieve existing non-expired match for CN='{0}'", expiredCN); } else if (retrievedCerts.Count > 1) { Console.WriteLine("FAIL: retrieved more than 1 match for CN='{0}'", expiredCN); } else if (retrievedCerts[0].Thumbprint.Equals(expiredTP)) { Console.WriteLine("FAIL: retrieved expired cert for CN='{0}': nbf: {1}, na: {2}", expiredCN, retrievedCerts[0].NotBefore, retrievedCerts[1].NotAfter); } } else if (retrievedCerts.Count > 0) { Console.WriteLine("FAIL: retrieved expired matches for CN='{0}'", expiredCN); } // try again, with 2 CNs retrievedCerts.Clear(); try { retrievedCerts = FindMatchingCertificates(StoreNamePersonal, StoreLocationLM, X509FindType.FindBySubjectName.ToString(), expiredCN, expectedCN, doTakeMostRecentOnly: true); } catch (Exception ex) { Console.WriteLine("Caught exception: {0}: {1}", ex.HResult, ex.Message); } if (retrievedCerts.Count < 1) { Console.WriteLine("FAIL: did not retrieve existing match for CNs={'{0}', '{1}'}", expiredCN, expectedCN); } if (retrievedCerts.Count > 1) { Console.WriteLine("FAIL: retrieved multiple matches for CNs={'{0}', '{1}'}", expiredCN, expectedCN); } if (retrievedCerts[0].Thumbprint.Equals(expiredTP)) { Console.WriteLine("FAIL: the cert retrieved by CN='{0}' (tp: {1}) is expired: nbf: {2}, na: {3}", expiredCN, retrievedCerts[0].Thumbprint, retrievedCerts[0].NotBefore, retrievedCerts[0].NotAfter); } // 4. ensure we get exactly one match (and it's the most recent) Console.WriteLine("\n** running test case 4"); retrievedCerts.Clear(); try { retrievedCerts = FindMatchingCertificates(StoreNamePersonal, StoreLocationLM, X509FindType.FindBySubjectName.ToString(), duplicateCN, String.Empty, doTakeMostRecentOnly: true); } catch (Exception ex) { Console.WriteLine("Caught exception: {0}: {1}", ex.HResult, ex.Message); } if (retrievedCerts.Count < 1) { Console.WriteLine("FAIL: did not retrieve existing match for CN='{0}'", duplicateCN); } if (retrievedCerts.Count > 1) { Console.WriteLine("FAIL: retrieved multiple matches for duplicate CN='{0}'", duplicateCN); } foreach (var duplicateCNCert in testCertCatalog[duplicateCN]) { // if the returned cert is more recent, and the duplicate cert is not expired, continue if (DateTime.Compare(retrievedCerts[0].NotBefore, duplicateCNCert.NotBefore) >= 0 || DateTime.Compare(DateTime.Now, duplicateCNCert.NotAfter) > 0) { continue; } Console.WriteLine( "FAIL: did not retrieve the most recent match for CN:'{0}': returned tp:{1}, nbf: {2}; expected tp:{3}, nbf: {4}", duplicateCN, retrievedCerts[0].Thumbprint, retrievedCerts[0].NotBefore, duplicateCNCert.Thumbprint, duplicateCNCert.NotBefore); break; } // 5. ensure we get a match by TP Console.WriteLine("\n** running test case 5"); retrievedCerts.Clear(); try { retrievedCerts = FindMatchingCertificates(StoreNamePersonal, StoreLocationLM, X509FindType.FindByThumbprint.ToString(), expectedCert.Thumbprint, String.Empty, doTakeMostRecentOnly: true); } catch (Exception ex) { Console.WriteLine("Caught exception: {0}: {1}", ex.HResult, ex.Message); } if (retrievedCerts.Count < 1) { Console.WriteLine("FAIL: did not retrieve existing match for TP='{0}'", expectedCert.Thumbprint); } if (retrievedCerts.Count > 1) { Console.WriteLine("FAIL: retrieved multiple matches for TP='{0}'", expectedCert.Thumbprint); } if (!VerifyCertsAreEqual(retrievedCerts[0], expectedCert)) { Console.WriteLine("FAIL: retrieved wrong certificate: actual TP='{0}'; expected TP='{1}'", retrievedCerts[0].Thumbprint, expectedCert.Thumbprint); } }
public bool InitializeAsClientAndGetStream(TcpClient tcpClient, cEncryptionSettings EncryptionSettings) { bool bSuccess = false; bSSLStreamIsOk = false; this.IgnoreCertificateErrors = EncryptionSettings.IgnoreCertificateErrors; ClientCertificates.Clear(); if (UseEncryption) { if (EncryptionSettings.AuthenticateAsClientUsingCertificate) { X509Certificate2 certificate = CreateCertificate(EncryptionSettings.ClientCertificateFile, EncryptionSettings.ClientCertificateFilePassword); if (certificate == null) { return(false); } ClientCertificates.Add(certificate); } sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ServerCertificateValidationCallback), new LocalCertificateSelectionCallback(SelectLocalCertificate)); try { if (EncryptionSettings.AuthenticateAsClientUsingCertificate) { sslStream.AuthenticateAsClient(EncryptionSettings.ServerName, ClientCertificates, EncryptionSettings.sslProtocols, EncryptionSettings.CheckCertificateRevocationList); } else { sslStream.AuthenticateAsClient(EncryptionSettings.ServerName, null, EncryptionSettings.sslProtocols, EncryptionSettings.CheckCertificateRevocationList); } RSMPGS.SysLog.SysLog(cSysLogAndDebug.Severity.Info, "Authentication succeeded"); LogSecurityLevel(sslStream); LogSecurityServices(sslStream); LogCertificateInformation(sslStream); bSSLStreamIsOk = true; bSuccess = true; } catch (Exception e) { RSMPGS.SysLog.SysLog(cSysLogAndDebug.Severity.Error, "Authentication failed, error: {0}", e.ToString()); } } else { try { networkStream = tcpClient.GetStream(); bSuccess = true; } catch (AuthenticationException e) { RSMPGS.SysLog.SysLog(cSysLogAndDebug.Severity.Error, "Could not get network stream, error: {0}", e.ToString()); } } return(bSuccess); }
private void MakeSecuredConnection() { uint method = 0x63c; this.TrEntry(method); try { StoreLocation localMachine; this.stream = new SslStream(this.client.GetStream(), false, new RemoteCertificateValidationCallback(this.ClientValidatingServerCertificate), new LocalCertificateSelectionCallback(this.FixClientCertificate)); base.TrText(method, "Created an instance of SSLStreams"); if (this.keyStore == "*SYSTEM") { localMachine = StoreLocation.LocalMachine; base.TrText(method, "Setting current certificate store as 'Computer'"); } else { localMachine = StoreLocation.CurrentUser; base.TrText(method, "Setting current certificate store as 'User'"); } X509Store store = new X509Store(StoreName.My, localMachine); base.TrText(method, "Created store object to access certificates"); store.Open(OpenFlags.OpenExistingOnly); base.TrText(method, "Opened store"); base.TrText(method, "Accessing certificate - " + this.clientCertName); X509Certificate2Collection clientCertificates = new X509Certificate2Collection(); X509Certificate2Enumerator enumerator = store.Certificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; if (current.FriendlyName.ToLower() == this.clientCertName) { clientCertificates.Add(current); } } Array values = Enum.GetValues(typeof(SslProtocols)); bool flag = Enum.IsDefined(typeof(SslProtocols), "Tls12"); base.TrText(method, "TLS12 supported - " + flag); if (((this.cipherSpec == null) || (this.cipherSpec == "*NEGOTIATE")) || (this.cipherSpec == string.Empty)) { if (flag) { foreach (SslProtocols protocols in values) { if (protocols.ToString() == "Tls12") { base.TrText(method, "Setting SslProtcol as TSL12"); this.sslProtocol = protocols; break; } } } else { base.TrText(method, "Setting SslProtocol as TLS"); this.sslProtocol = SslProtocols.Tls; } } else { values = Enum.GetValues(typeof(SslProtocols)); string sSLPrtocolVersionForCipher = MQCipherMappingTable.GetSSLPrtocolVersionForCipher(this.cipherSpec); if (sSLPrtocolVersionForCipher == null) { goto Label_02E8; } if (!(sSLPrtocolVersionForCipher == "SSL 3.0")) { if (sSLPrtocolVersionForCipher == "TLS 1.0") { goto Label_0263; } if (sSLPrtocolVersionForCipher == "TLS 1.2") { goto Label_027F; } goto Label_02E8; } this.sslProtocol = SslProtocols.Ssl3; base.TrText(method, "Setting SslProtol as Ssl3"); } goto Label_02FF; Label_0263: this.sslProtocol = SslProtocols.Tls; base.TrText(method, "Setting SslProtol as Tls"); goto Label_02FF; Label_027F: foreach (SslProtocols protocols2 in values) { if (protocols2.ToString() == "Tls12") { this.sslProtocol = protocols2; break; } } base.TrText(method, "Setting SslProtol as Tls12"); goto Label_02FF; Label_02E8: this.sslProtocol = SslProtocols.Default; base.TrText(method, "Setting SslProtocol as Default"); Label_02FF: base.TrText(method, "Starting SSL Authentication"); this.stream.AuthenticateAsClient("*", clientCertificates, this.sslProtocol, this.sslCertRevocationCheck); if (!this.stream.IsAuthenticated || !this.stream.IsEncrypted) { MQException exception = new MQException(2, 0x80b); this.client.Close(); throw exception; } store.Close(); store = null; clientCertificates.Clear(); clientCertificates = null; values = null; base.TrText(method, "SSL Authentication completed"); } catch (Exception exception2) { base.TrException(method, exception2); throw exception2; } finally { base.TrExit(method); } }