public void WeemoApi_RestSharpWeemoClient_GetAuthTokenAsync_should_return_AuthResponse_with_token() { // given var baseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var pathToPrivateCA = Path.Combine(baseDir, "Certs", "weemo-ca.pem").ToString(); var pathToClientCert = Path.Combine(baseDir, "Certs", "client.p12").ToString(); var config = new WeemoConfig(new CertLoader()) { AuthUrl = "https://oauths.weemo.com/auth/", ClientId = "CLIENT_ID_GOES_HERE", ClientSecret = "CLIENT_SECRET_GOES_HERE", ClientRootCertAuthorityIsInstalledOnServer = false } .SetClientRootCertAuthorityFromPath(pathToPrivateCA) .SetClientCertFromPath(pathToClientCert, "CERT_SECRET_GOES_HERE"); var validator = new CertificateValidator(config); var client = new RestSharpWeemoClient(config, validator); var request = new AuthRequest { Uid = "UNIQUE_USER_ID_GOES_HERE", Domain = "your-domain.com", LicenseType = WeemoLicenseTypes.premium }; // when var token = client.GetAuthTokenAsync(request).Result; // then Assert.IsNotNull(token); Assert.IsNotNull(token.Token); Assert.IsFalse(token.Token.Contains("error")); Assert.IsFalse(String.IsNullOrWhiteSpace(token.Token)); }
/// <summary> /// Handles a certificate validation error. /// </summary> void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { ManualResetEvent ev = new ManualResetEvent(false); Dispatcher.RunAsync( CoreDispatcherPriority.Normal, async () => { await GuiUtils.HandleCertificateValidationError(this, validator, e); ev.Set(); } ).AsTask().Wait(); ev.WaitOne(); }
static SslTests() { var rootKey = new Key(512); var interKey = new Key(512); var root = CaTests.CreateCert("cn=root.test", "cn=root.test", rootKey, rootKey); var inter = CaTests.CreateCert("cn=root.test", "cn=inter.test", rootKey, interKey); var subject1 = CaTests.CreateCert("cn=inter.test", "cn=server.test", interKey, new Key(512)); var subject2 = CaTests.CreateCert("cn=inter.test", "cn=client.test", interKey, new Key(512)); ServerCert = new CertificateLoader().FromPemString(subject1); ClientCert = new CertificateLoader().FromPemString(subject2); Validator = new CertificateValidator(new Certificate(root), new Certificate(inter)); }
public void validate_certificate_path() { var rootKey = new Key(512); var interKey = new Key(512); var finalKey = new Key(512); Certificate rootCert = GetCert("cn=root.test", rootKey, "cn=root.test", rootKey); Certificate interCert = GetCert("cn=inter.test", interKey, "cn=root.test", rootKey); Certificate finalCert = GetCert("cn=final.test", finalKey, "cn=inter.test", interKey); var certificates = new List<Certificate> {rootCert, interCert}; var certificateValidator = new CertificateValidator(certificates); var result = certificateValidator.Validate(finalCert); Console.WriteLine(result); }
/// <summary> /// Hier werden die Zertifikate überprüft /// Bei autoAccept aktiv wird diese Funktion obsolet /// </summary> /// <param name="validator"></param> /// <param name="e"></param> private static void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { //e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted) { //e.Accept = autoAccept; if (autoAccept) { Console.WriteLine("Accepted Certificate: {0}", e.Certificate.Subject); } else { Console.WriteLine("Rejected Certificate: {0}", e.Certificate.Subject); throw new Exception("Das Zertifikat {0} wurde nicht akzeptiert" + e.Certificate.Subject); } } }
public static void VerifyApplicationCertIntegrity(byte[] certificate, byte[] privateKey, string privateKeyPassword, string privateKeyFormat, byte[][] issuerCertificates) { X509Certificate2 newCert = new X509Certificate2(certificate); Assert.IsNotNull(newCert); X509Certificate2 newPrivateKeyCert = null; if (privateKeyFormat == "PFX") { newPrivateKeyCert = CertificateFactory.CreateCertificateFromPKCS12(privateKey, privateKeyPassword); } else if (privateKeyFormat == "PEM") { newPrivateKeyCert = CertificateFactory.CreateCertificateWithPEMPrivateKey(newCert, privateKey, privateKeyPassword); } else { Assert.Fail("Invalid private key format"); } Assert.IsNotNull(newPrivateKeyCert); // verify the public cert matches the private key Assert.IsTrue(CertificateFactory.VerifyRSAKeyPair(newCert, newPrivateKeyCert, true)); Assert.IsTrue(CertificateFactory.VerifyRSAKeyPair(newPrivateKeyCert, newPrivateKeyCert, true)); CertificateIdentifierCollection issuerCertIdCollection = new CertificateIdentifierCollection(); foreach (var issuer in issuerCertificates) { var issuerCert = new X509Certificate2(issuer); Assert.IsNotNull(issuerCert); issuerCertIdCollection.Add(new CertificateIdentifier(issuerCert)); } // verify cert with issuer chain CertificateValidator certValidator = new CertificateValidator(); CertificateTrustList issuerStore = new CertificateTrustList(); CertificateTrustList trustedStore = new CertificateTrustList(); trustedStore.TrustedCertificates = issuerCertIdCollection; certValidator.Update(trustedStore, issuerStore, null); Assert.That(() => { certValidator.Validate(newCert); }, Throws.Exception); issuerStore.TrustedCertificates = issuerCertIdCollection; certValidator.Update(issuerStore, trustedStore, null); certValidator.Validate(newCert); }
/// <summary> /// Handles a certificate validation error. /// </summary> private void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { try { if (m_applicationConfiguration.SecurityConfiguration != null && m_applicationConfiguration.SecurityConfiguration.AutoAcceptUntrustedCertificates && e.Error != null && e.Error.Code == StatusCodes.BadCertificateUntrusted) { e.Accept = true; Utils.Trace((int)Utils.TraceMasks.Security, "Automatically accepted certificate: {0}", e.Certificate.Subject); } } catch (Exception exception) { Utils.Trace(exception, "Error accepting certificate."); } }
public void Asynchronous_Receive_RemoteCertificateRevokedUnknown() { CertificateValidator.SetError( (c, u) => (u == X509KeyUsageFlags.NonRepudiation) ? CertificateErrors.RevokedUnknown : CertificateErrors.None); RunAsynchronousReceive( postValidation: () => { Assert.AreEqual(0, MockFactory.Helsenorge.Asynchronous.Messages.Count); Assert.AreEqual(1, MockFactory.OtherParty.Error.Messages.Count); Assert.IsNotNull(MockLoggerProvider.FindEntry(EventIds.RemoteCertificateRevocation)); CheckError(MockFactory.OtherParty.Error.Messages, "transport:revoked-certificate", "Unable to determine revocation status", string.Empty); }, wait: () => _completedCalled, received: (m) => { Assert.IsTrue(m.SignatureError != CertificateErrors.None); }, messageModification: (m) => { }); }
void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { if (InvokeRequired) { Invoke(new CertificateValidationEventHandler(CertificateValidator_CertificateValidation), validator, e); return; } try { GuiUtils.HandleCertificateValidationError(this, validator, e); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
private static void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { string logPrefix = $"{_logClassPrefix}:CertificateValidator_CertificateValidation:"; if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted) { e.Accept = AutoAccept; if (AutoAccept) { Logger.Verbose($"{logPrefix} Accepted Certificate: {0}", e.Certificate.Subject); } else { Logger.Warning($"{logPrefix} Rejected Certificate: {0}", e.Certificate.Subject); } } }
void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { if (InvokeRequired) { Invoke(new CertificateValidationEventHandler(CertificateValidator_CertificateValidation), validator, e); return; } try { GuiUtils.HandleCertificateValidationError(this, validator, e); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
/// <summary> /// Verifies that a certificate user token is trusted. /// </summary> private void VerifyUserTokenCertificate(X509Certificate2 certificate) { try { if (m_certificateValidator != null) { m_certificateValidator.Validate(certificate); } else { CertificateValidator.Validate(certificate); } } catch (Exception e) { TranslationInfo info; StatusCode result = StatusCodes.BadIdentityTokenRejected; ServiceResultException se = e as ServiceResultException; if (se != null && se.StatusCode == StatusCodes.BadCertificateUseNotAllowed) { info = new TranslationInfo( "InvalidCertificate", "en-US", "'{0}' is an invalid user certificate.", certificate.Subject); result = StatusCodes.BadIdentityTokenInvalid; } else { // construct translation object with default text. info = new TranslationInfo( "UntrustedCertificate", "en-US", "'{0}' is not a trusted user certificate.", certificate.Subject); } // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( result, info.Key, LoadServerProperties().ProductUri, new LocalizedText(info))); } }
/// <summary> /// Verifies that a certificate user token is trusted. /// </summary> private void VerifyUserTokenCertificate(X509Certificate2 certificate) { try { CertificateValidator.Validate(certificate); // determine if self-signed. var isSelfSigned = Utils.CompareDistinguishedName(certificate.Subject, certificate.Issuer); // do not allow self signed application certs as user token if (isSelfSigned && Utils.HasApplicationURN(certificate)) { throw new ServiceResultException(StatusCodes.BadCertificateUseNotAllowed); } } catch (Exception e) { TranslationInfo info; StatusCode result = StatusCodes.BadIdentityTokenRejected; var se = e as ServiceResultException; if (se != null && se.StatusCode == StatusCodes.BadCertificateUseNotAllowed) { info = new TranslationInfo( "InvalidCertificate", "en-US", "'{0}' is an invalid user certificate.", certificate.Subject); result = StatusCodes.BadIdentityTokenInvalid; } else { // construct translation object with default text. info = new TranslationInfo( "UntrustedCertificate", "en-US", "'{0}' is not a trusted user certificate.", certificate.Subject); } // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( result, info.Key, LoadServerProperties().ProductUri, new LocalizedText(info))); } }
internal void ValidateResponseCertificate(SignedXmlWithAgnosticId signed) { var signature = ResponseContainer.HeaderBinarySecurityToken.InnerText; var value = Convert.FromBase64String(signature); var responseCertificate = new X509Certificate2(value); const string organizationNumberDirektoratetForForvaltningOgIkt = "991825827"; var responseCertificateValidationResult = CertificateValidator.ValidateCertificateAndChain( responseCertificate, organizationNumberDirektoratetForForvaltningOgIkt, Environment.GodkjenteKjedeSertifikaterForRespons ); if (responseCertificateValidationResult.Type != CertificateValidationType.Valid) { throw new SecurityException($"Sertifikatet som ble mottatt i responsen er ikke gyldig. Grunnen er '{responseCertificateValidationResult.Type.ToNorwegianString()}', med melding '{responseCertificateValidationResult.Message}'"); } }
/// <summary> /// Handles a certificate validation error. /// </summary> /// <param name="caller">The caller's text is used as the caption of the <see cref="MessageBox"/> shown to provide details about the error.</param> /// <param name="validator">The validator (not used).</param> /// <param name="e">The <see cref="Opc.Ua.CertificateValidationEventArgs"/> instance event arguments provided when a certificate validation error occurs.</param> public static async Task HandleCertificateValidationError(Page caller, CertificateValidator validator, CertificateValidationEventArgs e) { StringBuilder buffer = new StringBuilder(); buffer.AppendFormat("Certificate could not validated: {0}\r\n\r\n", e.Error.StatusCode); buffer.AppendFormat("Subject: {0}\r\n", e.Certificate.Subject); buffer.AppendFormat("Issuer: {0}\r\n", (e.Certificate.Subject == e.Certificate.Issuer) ? "Self-signed" : e.Certificate.Issuer); buffer.AppendFormat("Thumbprint: {0}\r\n\r\n", e.Certificate.Thumbprint); buffer.AppendFormat("Accept anyways?"); MessageDlg dialog = new MessageDlg(buffer.ToString(), MessageDlgButton.Yes, MessageDlgButton.No); MessageDlgButton result = await dialog.ShowAsync(); if (result == MessageDlgButton.Yes) { e.Accept = true; } }
public static bool ValidateCertificateSignatureWithChain(Certificate certificate) { Certificate caCertificate = FindIssuerCaCertificate(certificate); if (!caCertificate.IsLoaded) { Logger.log("Can not find issuer certificate"); return(false); } if (!CertificateValidator.CheckCertificateWithWithCaCertificate(certificate, caCertificate)) { Logger.log("Can not find validate validity with issuer certificate validity"); return(false); } return(true); }
/// <summary> /// Handles a certificate validation error. /// </summary> /// <param name="caller">The caller's text is used as the caption of the <see cref="MessageBox"/> shown to provide details about the error.</param> /// <param name="validator">The validator (not used).</param> /// <param name="e">The <see cref="Opc.Ua.CertificateValidationEventArgs"/> instance event arguments provided when a certificate validation error occurs.</param> public static void HandleCertificateValidationError(Form caller, CertificateValidator validator, CertificateValidationEventArgs e) { StringBuilder buffer = new StringBuilder(); buffer.AppendFormat("Certificate could not validated: {0}\r\n\r\n", e.Error.StatusCode); buffer.AppendFormat("Subject: {0}\r\n", e.Certificate.Subject); buffer.AppendFormat("Issuer: {0}\r\n", (e.Certificate.Subject == e.Certificate.Issuer)?"Self-signed":e.Certificate.Issuer); buffer.AppendFormat("Valid From: {0}\r\n", e.Certificate.NotBefore); buffer.AppendFormat("Valid To: {0}\r\n", e.Certificate.NotAfter); buffer.AppendFormat("Thumbprint: {0}\r\n\r\n", e.Certificate.Thumbprint); buffer.AppendFormat("Accept anyways?"); if (MessageBox.Show(buffer.ToString(), caller.Text, MessageBoxButtons.YesNo) == DialogResult.Yes) { e.Accept = true; } }
/// <summary> /// UI: handle server certificate validation /// and prompt for user interaction if required. /// </summary> void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { ManualResetEvent ev = new ManualResetEvent(false); Dispatcher.RunAsync( CoreDispatcherPriority.Normal, async() => { await GuiUtils.HandleCertificateValidationError(this, validator, e); if (e.Accept) { MessageDialog showDialog = new MessageDialog("Would you like to save this certificate?"); showDialog.Commands.Add(new UICommand("Save") { Id = 0 }); showDialog.Commands.Add(new UICommand("Cancel") { Id = 1 }); showDialog.DefaultCommandIndex = 1; showDialog.CancelCommandIndex = 1; var result = await showDialog.ShowAsync(); if ((int)result.Id == 0) { try { byte[] cert = e.Certificate.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert); string issuerName = e.Certificate.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true); string filePath = Path.Combine(m_cert_full_path, String.Format("{0} [{1}].der", issuerName, e.Certificate.Thumbprint)); File.WriteAllBytes(filePath, cert); } catch (Exception) { } } } progringConnection.IsActive = true; ev.Set(); } ).AsTask().Wait(); ev.WaitOne(); }
public static bool AddSslCertificate(byte[] certificateHash, byte[] encodedCert) { Logger.log("Checking SSL Certificate is added before"); if (CertificateStorageManager.IsSSLCertificateAddedBefore(certificateHash)) { Logger.log("SSL Certificate is added before"); return(false); } Logger.log("Trying to parse SSL Certificate"); Certificate sslCertificate = CertificateParser.Parse(encodedCert); if (!sslCertificate.IsLoaded) { Logger.log("Can not parse SSL Certificate"); return(false); } Logger.log("Checking SSL Certificate Validity Period"); if (!CertificateValidator.CheckValidityPeriod(sslCertificate)) { Logger.log("SSL Certificate validity period is invalid"); return(false); } Logger.log("Checking SSL Certificate Fields"); if (!CertificateValidator.ValidateSslCertificateFields(sslCertificate)) { Logger.log("SSL Certificate Fields are invalid"); return(false); } Logger.log("Validating SSL Certificate With Chain"); if (!CertificateChainValidator.ValidateCertificateSignatureWithChain(sslCertificate)) { Logger.log("Can not validate SSL Certificate Signature With Chain"); return(false); } Logger.log("Adding SSL Certificate To Storage"); CertificateStorageManager.AddEndEntityCertificateToStorage(sslCertificate, certificateHash, encodedCert); return(true); }
private void VerifyUserTokenCertificate(X509Certificate2 certificate) { try { CertificateValidator.Validate(certificate); } catch (Exception e) { TranslationInfo info; StatusCode result = StatusCodes.BadIdentityTokenRejected; if (e is ServiceResultException se && se.StatusCode == StatusCodes.BadCertificateUseNotAllowed) { info = new TranslationInfo( "InvalidCertificate", "en-US", $"'{certificate.Subject}' is an invalid user certificate."); result = StatusCodes.BadIdentityTokenInvalid; }
public void Asynchronous_Receive_LocalCertificateMultiple() { CertificateValidator.SetError( (c, u) => (u == X509KeyUsageFlags.DataEncipherment) ? CertificateErrors.StartDate | CertificateErrors.EndDate : CertificateErrors.None); RunAsynchronousReceive( postValidation: () => { Assert.AreEqual(0, MockFactory.Helsenorge.Asynchronous.Messages.Count); Assert.AreEqual(0, MockFactory.OtherParty.Error.Messages.Count); Assert.IsNotNull(MockLoggerProvider.FindEntry(EventIds.LocalCertificate)); }, wait: () => _completedCalled, received: (m) => { Assert.IsTrue(m.DecryptionError != CertificateErrors.None); }, messageModification: (m) => { }); }
public void Asynchronous_Receive_RemoteCertificateMultiple() { CertificateValidator.SetError( (c, u) => (u == X509KeyUsageFlags.NonRepudiation) ? CertificateErrors.StartDate | CertificateErrors.EndDate : CertificateErrors.None); RunAsynchronousReceive( postValidation: () => { Assert.AreEqual(0, MockFactory.Helsenorge.Asynchronous.Messages.Count); Assert.AreEqual(1, MockFactory.OtherParty.Error.Messages.Count); Assert.IsNotNull(MockLoggerProvider.FindEntry(EventIds.RemoteCertificate)); CheckError(MockFactory.OtherParty.Error.Messages, "transport:invalid-certificate", "More than one error with certificate", string.Empty); }, wait: () => _completedCalled, received: (m) => { Assert.IsTrue(m.SignatureError != CertificateErrors.None); }, messageModification: (m) => { }); }
public void CertificateIsValid(IEnumerable <Task> tasks) { InstallParam p = new InstallParam("somename", "somevalue"); tasks.First().LocalParams.Add(p); CertificateValidator val = Substitute.ForPartsOf <CertificateValidator>(); val.WhenForAnyArgs(a => a.FindCertificates(null)).DoNotCallBase(); X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Add(new X509Certificate2()); val.FindCertificates(null).ReturnsForAnyArgs(collection); val.Data["StoreName"] = "Root"; val.Data["ParamNames"] = p.Name; val.WhenForAnyArgs(a => a.ValidateChain(null, null)).DoNotCallBase(); val.ValidateChain(null, null).ReturnsForAnyArgs(true); Assert.DoesNotContain(val.Evaluate(tasks), r => r.State == Sitecore9Installer.Validation.ValidatorState.Error); val.Received().ValidateCertificate(collection[0]); }
void m_Server_CertificateEvent(CertificateValidator validator, CertificateValidationEventArgs e) { // Ask user if he wants to trust the certificate DialogResult result = MessageBox.Show( "Do you want to accept the untrusted server certificate: \n" + "\nSubject Name: " + e.Certificate.SubjectName.Name + "\nIssuer Name: " + e.Certificate.IssuerName.Name, "Untrusted Server Certificate", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { // If the certificate is stored in the trust list, the user is not asked again e.Accept = true; } else { e.Accept = false; } }
/// <summary> /// Handles a certificate validation error. /// </summary> /// <param name="caller">The caller's text is used as the caption of the <see cref="MessageBox"/> shown to provide details about the error.</param> /// <param name="validator">The validator (not used).</param> /// <param name="e">The <see cref="Opc.Ua.CertificateValidationEventArgs"/> instance event arguments provided when a certificate validation error occurs.</param> public static void HandleCertificateValidationError(Form caller, CertificateValidator validator, CertificateValidationEventArgs e) { StringBuilder buffer = new StringBuilder(); buffer.AppendFormat("Certificate could not be validated: {0}\r\n\r\n", e.Error.StatusCode); buffer.AppendFormat("Subject: {0}\r\n", e.Certificate.Subject); buffer.AppendFormat("Issuer: {0}\r\n", (e.Certificate.Subject == e.Certificate.Issuer)?"Self-signed":e.Certificate.Issuer); buffer.AppendFormat("Valid From: {0}\r\n", e.Certificate.NotBefore); buffer.AppendFormat("Valid To: {0}\r\n", e.Certificate.NotAfter); buffer.AppendFormat("Thumbprint: {0}\r\n\r\n", e.Certificate.Thumbprint); buffer.AppendFormat("The security certificate was not issued by a trusted certificate authority. "); buffer.AppendFormat("Security certificate problems may indicate an attempt to intercept any data you send "); buffer.AppendFormat("to a server or to allow an untrusted client to connect to your server."); buffer.AppendFormat("\r\n\r\nAccept anyway?"); if (MessageBox.Show(buffer.ToString(), caller.Text, MessageBoxButtons.YesNo) == DialogResult.Yes) { e.Accept = true; } }
/// <summary> /// Checks if the certificate is valid /// </summary> /// <param name="certificate">The certificate to check</param> /// <returns>boolean stating whether the certificate is valid (true) or not (false)</returns> /// <exception cref="CheckCertificateValidUnexpectedException">This exception is thrown, if an unexpected exception is thrown during the method</exception> public bool CheckCertificateValidation(X509Certificate2 certificate) { bool isValid = false; try { CertificateValidator.CheckCertificateExpired(certificate); isValid = true; } catch (CertificateExpiredException) { isValid = false; } catch (ArgumentNullException) { throw; } catch (CryptographicUnexpectedOperationException) { throw; } catch (CryptographicException) { throw; } catch (Exception e) { throw new CheckCertificateValidUnexpectedException(e); } return(isValid); }
/// <summary> /// Handles a certificate validation error. /// </summary> /// <param name="caller">The caller's text is used as the caption of the <see cref="MessageBox"/> shown to provide details about the error.</param> /// <param name="validator">The validator (not used).</param> /// <param name="e">The <see cref="Opc.Ua.CertificateValidationEventArgs"/> instance event arguments provided when a certificate validation error occurs.</param> public static async Task HandleCertificateValidationError(Page caller, CertificateValidator validator, CertificateValidationEventArgs e) { StringBuilder buffer = new StringBuilder(); buffer.AppendFormat("Certificate could not be validated: {0}\r\n\r\n", e.Error.StatusCode); buffer.AppendFormat("Subject: {0}\r\n", e.Certificate.Subject); buffer.AppendFormat("Issuer: {0}\r\n", (e.Certificate.Subject == e.Certificate.Issuer) ? "Self-signed" : e.Certificate.Issuer); buffer.AppendFormat("Thumbprint: {0}\r\n\r\n", e.Certificate.Thumbprint); buffer.AppendFormat("The security certificate was not issued by a trusted certificate authority.\r\n"); buffer.AppendFormat("Security certificate problems may indicate an attempt to intercept any data you send\r\n"); buffer.AppendFormat("to a server or to allow an untrusted client to connect to your server.\r\n"); buffer.AppendFormat("\r\nAccept anyway?"); MessageDlg dialog = new MessageDlg(buffer.ToString(), MessageDlgButton.Yes, MessageDlgButton.No); MessageDlgButton result = await dialog.ShowAsync(); if (result == MessageDlgButton.Yes) { e.Accept = true; } }
public static void VerifyApplicationCertIntegrity( X509Certificate2 newCert, Key privateKey, X509Certificate2Collection issuerCertificates) { Assert.NotNull(newCert); Assert.True(privateKey.HasPrivateKey()); if (privateKey != null) { using (var newPrivateKeyCert = new X509Certificate2(newCert.RawData) { PrivateKey = privateKey.ToRSA() }) { Assert.True(newPrivateKeyCert.HasPrivateKey); Assert.NotNull(newPrivateKeyCert); Assert.True(newPrivateKeyCert.HasPrivateKey); // verify the public cert matches the private key Assert.True(CertificateFactory.VerifyRSAKeyPair(newCert, newPrivateKeyCert, true)); Assert.True(CertificateFactory.VerifyRSAKeyPair(newPrivateKeyCert, newPrivateKeyCert, true)); } } var issuerCertIdCollection = new CertificateIdentifierCollection(); foreach (var issuerCert in issuerCertificates) { issuerCertIdCollection.Add(new CertificateIdentifier(issuerCert)); } // verify cert with issuer chain var certValidator = new CertificateValidator(); var issuerStore = new CertificateTrustList(); var trustedStore = new CertificateTrustList { TrustedCertificates = issuerCertIdCollection }; certValidator.Update(trustedStore, issuerStore, null); Assert.Throws <ServiceResultException>(() => certValidator.Validate(newCert)); issuerStore.TrustedCertificates = issuerCertIdCollection; certValidator.Update(issuerStore, trustedStore, null); certValidator.Validate(newCert); }
private void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted) { if (AutoAccept) { if (!LogConsole) { Console.WriteLine("Accepted Certificate: {0}", e.Certificate.Subject); } Utils.Trace(Utils.TraceMasks.Security, "Accepted Certificate: {0}", e.Certificate.Subject); e.Accept = true; return; } } if (!LogConsole) { Console.WriteLine("Rejected Certificate: {0} {1}", e.Error, e.Certificate.Subject); } Utils.Trace(Utils.TraceMasks.Security, "Rejected Certificate: {0} {1}", e.Error, e.Certificate.Subject); }
/// <summary> /// Validates the certificate. /// </summary> private void CertificateValidator_CertificateValidation(CertificateValidator sender, CertificateValidationEventArgs e) { if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted) { e.Accept = options.AutoAccept; if (options.AutoAccept) { dsLog.WriteAction(Locale.IsRussian ? "Принятый сертификат: {0}" : "Accepted certificate: {0}", e.Certificate.Subject); } else { dsLog.WriteError(Locale.IsRussian ? "Отклоненный сертификат: {0}" : "Rejected certificate: {0}", e.Certificate.Subject); } } }
/// <summary> /// Validates the certificate. /// </summary> private void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted) { e.Accept = autoAccept; if (autoAccept) { WriteToLog(string.Format(Localization.UseRussian ? "Принятый сертификат: {0}" : "Accepted certificate: {0}", e.Certificate.Subject)); } else { WriteToLog(string.Format(Localization.UseRussian ? "Отклоненный сертификат: {0}" : "Rejected certificate: {0}", e.Certificate.Subject)); } } }
public void Asynchronous_Receive_RemoteCertificateMissing() { CertificateValidator.SetError((c, u) => CertificateErrors.Missing); RunAsynchronousReceive( postValidation: () => { Assert.AreEqual(0, MockFactory.Helsenorge.Asynchronous.Messages.Count); Assert.AreEqual(0, MockFactory.OtherParty.Error.Messages.Count); var error = MockLoggerProvider.Entries .Where(a => a.LogLevel == LogLevel.Warning && a.Message.Contains("Certificate is missing for message. MessageFunction: DIALOG_INNBYGGER_EKONTAKT")) .ToList(); Assert.AreEqual(1, error.Count); Assert.IsTrue(error.Single().Message.Contains("MessageFunction: DIALOG_INNBYGGER_EKONTAKT FromHerId: 93252 ToHerId: 93238")); }, wait: () => _completedCalled, received: (m) => { Assert.IsTrue(m.SignatureError == CertificateErrors.Missing); }, messageModification: (m) => { }); }
public void SPMetadataGeneration_create_file() { ////ARRANGE var result = false; var path = @"D:\Dan\Software\Apira\SPMetadata\SPMetadataTest.xml"; var metadataWriter = new TestMetadatWriter(el => { if (File.Exists(path)) { File.Delete(path); } using (var writer = XmlWriter.Create(path)) { el.WriteTo(writer); writer.Flush(); } result = true; }); var logger = new LogProviderMock(); var contextBuilder = new InlineMetadataContextBuilder(); var metadataRequest = new MetadataGenerateRequest(MetadataType.SP, "local"); var metadatContext = contextBuilder.BuildContext(metadataRequest); var context = new FederationPartyConfiguration(metadataRequest.FederationPartyId, "localhost"); var configurationProvider = new CertificateValidationConfigurationProvider(); var certificateValidator = new CertificateValidator(configurationProvider); var ssoCryptoProvider = new CertificateManager(logger); var metadataSerialiser = new FederationMetadataSerialiser(certificateValidator, logger); var metadataDispatcher = new FederationMetadataDispatcherMock(() => new[] { metadataWriter }); var sPSSOMetadataProvider = new SPSSOMetadataProvider(metadataDispatcher, ssoCryptoProvider, metadataSerialiser, g => context, logger); //ACT sPSSOMetadataProvider.CreateMetadata(metadataRequest); //ASSERT Assert.IsTrue(result); }
/// <summary> /// Called when a certificate cannot be validated. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="Opc.Ua.CertificateValidationEventArgs"/> instance containing the event data.</param> void CertificateValidator_CertificateValidation(CertificateValidator sender, CertificateValidationEventArgs e) { // need to dispatch to the main UI thread. if (InvokeRequired) { Invoke(new CertificateValidationEventHandler(CertificateValidator_CertificateValidation), sender, e); return; } try { e.Accept = true; /* * // prompt user. * switch (new AcceptCertificateDlg().ShowDialog(e)) * { * case AcceptCertificateOptions.AcceptAlwaysForAll: * case AcceptCertificateOptions.AcceptAlwaysForCurrent: * case AcceptCertificateOptions.AcceptOnceForCurrent: * { * // TBD - update configuration to make the acceptance permenent. * e.Accept = true; * break; * } * * case AcceptCertificateOptions.RejectAlways: * { * // TBD - update configuration to make the rejection permenent. * e.Accept = false; * break; * } * } */ } catch (Exception exception) { MessageBox.Show(exception.Message); } }
/// <summary> /// Initializes the datastore with the server configuration. /// </summary> /// <param name="serverDescription">The server description.</param> /// <param name="configuration">The configuration.</param> /// <param name="messageContext">The message context.</param> /// <param name="certificateValidator">The certificate validator.</param> /// <param name="instanceCertificate">The instance certificate.</param> public ServerInternalData( ServerProperties serverDescription, ApplicationConfiguration configuration, ServiceMessageContext messageContext, CertificateValidator certificateValidator, X509Certificate2 instanceCertificate) { m_serverDescription = serverDescription; m_configuration = configuration; m_messageContext = messageContext; m_endpointAddresses = new List <Uri>(); foreach (string baseAddresses in m_configuration.ServerConfiguration.BaseAddresses) { Uri url = Utils.ParseUri(baseAddresses); if (url != null) { m_endpointAddresses.Add(url); } } m_namespaceUris = m_messageContext.NamespaceUris; m_factory = m_messageContext.Factory; m_serverUris = new StringTable(); m_typeTree = new TypeTable(m_namespaceUris); #if LEGACY_CORENODEMANAGER m_typeSources = new TypeSourceTable(); #endif // add the server uri to the server table. m_serverUris.Append(m_configuration.ApplicationUri); // create the default system context. m_defaultSystemContext = new ServerSystemContext(this); }
/// <summary> /// Initializes the datastore with the server configuration. /// </summary> /// <param name="serverDescription">The server description.</param> /// <param name="configuration">The configuration.</param> /// <param name="messageContext">The message context.</param> /// <param name="certificateValidator">The certificate validator.</param> /// <param name="instanceCertificate">The instance certificate.</param> public ServerInternalData( ServerProperties serverDescription, ApplicationConfiguration configuration, ServiceMessageContext messageContext, CertificateValidator certificateValidator, X509Certificate2 instanceCertificate) { m_serverDescription = serverDescription; m_configuration = configuration; m_messageContext = messageContext; m_endpointAddresses = new List<Uri>(); foreach (string baseAddresses in m_configuration.ServerConfiguration.BaseAddresses) { Uri url = Utils.ParseUri(baseAddresses); if (url != null) { m_endpointAddresses.Add(url); } } m_namespaceUris = m_messageContext.NamespaceUris; m_factory = m_messageContext.Factory; m_serverUris = new StringTable(); m_typeTree = new TypeTable(m_namespaceUris); #if LEGACY_CORENODEMANAGER m_typeSources = new TypeSourceTable(); #endif // add the server uri to the server table. m_serverUris.Append(m_configuration.ApplicationUri); // create the default system context. m_defaultSystemContext = new ServerSystemContext(this); }
/// <summary> /// Handles a certificate validation error. /// </summary> /// <param name="caller">The caller's text is used as the caption of the <see cref="MessageBox"/> shown to provide details about the error.</param> /// <param name="validator">The validator (not used).</param> /// <param name="e">The <see cref="Opc.Ua.CertificateValidationEventArgs"/> instance event arguments provided when a certificate validation error occurs.</param> public static void HandleCertificateValidationError(Form caller, CertificateValidator validator, CertificateValidationEventArgs e) { StringBuilder buffer = new StringBuilder(); buffer.AppendFormat("Certificate could not be validated: {0}\r\n\r\n", e.Error.StatusCode); buffer.AppendFormat("Subject: {0}\r\n", e.Certificate.Subject); buffer.AppendFormat("Issuer: {0}\r\n", (e.Certificate.Subject == e.Certificate.Issuer)?"Self-signed":e.Certificate.Issuer); buffer.AppendFormat("Valid From: {0}\r\n", e.Certificate.NotBefore); buffer.AppendFormat("Valid To: {0}\r\n", e.Certificate.NotAfter); buffer.AppendFormat("Thumbprint: {0}\r\n\r\n", e.Certificate.Thumbprint); buffer.AppendFormat("The security certificate was not issued by a trusted certificate authority. "); buffer.AppendFormat("Security certificate problems may indicate an attempt to intercept any data you send "); buffer.AppendFormat("to a server or to allow an untrusted client to connect to your server."); buffer.AppendFormat("\r\n\r\nAccept anyway?"); if (MessageBox.Show(buffer.ToString(), caller.Text, MessageBoxButtons.YesNo) == DialogResult.Yes) { e.Accept = true; } }
/// <summary> /// Handles a certificate validation error. /// </summary> void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { try { Opc.Ua.Client.Controls.GuiUtils.HandleCertificateValidationError(this, validator, e); } catch (Exception exception) { Opc.Ua.Client.Controls.GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
/// <summary> /// Handles a certificate validation error. /// </summary> private void CertificateValidator_CertificateValidation(CertificateValidator sender, CertificateValidationEventArgs e) { if (this.InvokeRequired) { this.Invoke(new CertificateValidationEventHandler(CertificateValidator_CertificateValidation), sender, e); return; } try { e.Accept = m_configuration.SecurityConfiguration.AutoAcceptUntrustedCertificates; if (!m_configuration.SecurityConfiguration.AutoAcceptUntrustedCertificates) { DialogResult result = MessageBox.Show( e.Certificate.Subject, "Untrusted Certificate", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); e.Accept = (result == DialogResult.Yes); } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
/// <summary> /// Uses the UA validation logic for HTTPS certificates. /// </summary> /// <param name="validator">The validator.</param> public static void SetUaValidationForHttps(CertificateValidator validator) { m_validator = validator; }
/// <summary> /// Handles a certificate validation error. /// </summary> /// <param name="caller">The caller's text is used as the caption of the <see cref="MessageBox"/> shown to provide details about the error.</param> /// <param name="validator">The validator (not used).</param> /// <param name="e">The <see cref="Opc.Ua.CertificateValidationEventArgs"/> instance event arguments provided when a certificate validation error occurs.</param> public static async Task HandleCertificateValidationError(Page caller, CertificateValidator validator, CertificateValidationEventArgs e) { StringBuilder buffer = new StringBuilder(); buffer.AppendFormat("Certificate could not validated: {0}\r\n\r\n", e.Error.StatusCode); buffer.AppendFormat("Subject: {0}\r\n", e.Certificate.Subject); buffer.AppendFormat("Issuer: {0}\r\n", (e.Certificate.Subject == e.Certificate.Issuer) ? "Self-signed" : e.Certificate.Issuer); buffer.AppendFormat("Thumbprint: {0}\r\n\r\n", e.Certificate.Thumbprint); buffer.AppendFormat("Accept anyways?"); MessageDlg dialog = new MessageDlg(buffer.ToString(), MessageDlgButton.Yes, MessageDlgButton.No); MessageDlgButton result = await dialog.ShowAsync(); if (result == MessageDlgButton.Yes) { e.Accept = true; } }
/// <summary> /// Accepts server certificates. /// </summary> void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { // always safe to trust servers when connecting as a test application. e.Accept = true; }
/// <summary> /// Checks that the domains in the certificate match the current host. /// </summary> private void RegistrationValidator_CertificateValidation(CertificateValidator sender, CertificateValidationEventArgs e) { Task t = Task.Run(async () => { System.Net.IPAddress[] targetAddresses = await Utils.GetHostAddresses(Utils.GetHostName()); foreach (string domain in Utils.GetDomainsFromCertficate(e.Certificate)) { System.Net.IPAddress[] actualAddresses = await Utils.GetHostAddresses(domain); foreach (System.Net.IPAddress actualAddress in actualAddresses) { foreach (System.Net.IPAddress targetAddress in targetAddresses) { if (targetAddress.Equals(actualAddress)) { e.Accept = true; return; } } } } }); t.Wait(); }
/// <summary> /// Handles a certificate validation error. /// </summary> /// <param name="caller">The caller's text is used as the caption of the <see cref="MessageBox"/> shown to provide details about the error.</param> /// <param name="validator">The validator (not used).</param> /// <param name="e">The <see cref="Opc.Ua.CertificateValidationEventArgs"/> instance event arguments provided when a certificate validation error occurs.</param> public static void HandleCertificateValidationError(Form caller, CertificateValidator validator, CertificateValidationEventArgs e) { StringBuilder buffer = new StringBuilder(); buffer.AppendFormat("Certificate could not validated: {0}\r\n\r\n", e.Error.StatusCode); buffer.AppendFormat("Subject: {0}\r\n", e.Certificate.Subject); buffer.AppendFormat("Issuer: {0}\r\n", (e.Certificate.Subject == e.Certificate.Issuer)?"Self-signed":e.Certificate.Issuer); buffer.AppendFormat("Valid From: {0}\r\n", e.Certificate.NotBefore); buffer.AppendFormat("Valid To: {0}\r\n", e.Certificate.NotAfter); buffer.AppendFormat("Thumbprint: {0}\r\n\r\n", e.Certificate.Thumbprint); buffer.AppendFormat("Accept anyways?"); if (MessageBox.Show(buffer.ToString(), caller.Text, MessageBoxButtons.YesNo) == DialogResult.Yes) { e.Accept = true; } }
/// <summary> /// Handles a certificate validation error. /// </summary> private static void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { try { if (e.Error != null && e.Error.Code == StatusCodes.BadCertificateUntrusted) { e.Accept = true; Utils.Trace((int)Utils.TraceMasks.Security, "Automatically accepted certificate: {0}", e.Certificate.Subject); } } catch (Exception exception) { Utils.Trace(exception, "Error accepting certificate."); } }
/// <summary> /// Always accept server certificates. /// </summary> void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { e.Accept = true; }
/// <summary> /// Validates a certificate and adds it to the trust list. /// </summary> private void ValidateAndImport(CertificateStoreIdentifier store, X509Certificate2 certificate) { if (store == null || certificate == null) { return; } // validate the certificate using the trust lists for the certificate tool. try { CertificateValidator validator = new CertificateValidator(); validator.Update(m_configuration); validator.Validate(certificate); } catch (ServiceResultException exception) { if (!HandleValidationError(certificate, exception)) { return; } } // confirm import. StringBuilder buffer = new StringBuilder(); buffer.Append("You are adding this certificate to a trust list that may be shared with other applications."); buffer.Append("\r\n"); buffer.Append("\r\n"); buffer.Append("Would you still like to accept the certificate?\r\n"); buffer.Append("\r\n"); buffer.Append("Target Trust List = "); buffer.Append(store.ToString()); buffer.Append("\r\n"); buffer.Append("Certificate to Add = "); buffer.Append(certificate.Subject); DialogResult result = new YesNoDlg().ShowDialog(buffer.ToString(), "Import Certificate to Trust List"); if (result != DialogResult.Yes) { return; } // update store. ICertificateStore physicalStore = store.OpenStore(); if (physicalStore.FindByThumbprint(certificate.Thumbprint) == null) { physicalStore.Add(new X509Certificate2(certificate.RawData)); } }