From 9781f1b1a7d3ef551eab27a415ed79993087e955 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aleksander=20Aas=20Sja=CC=8Afjell?= Date: Mon, 26 Sep 2016 16:07:12 +0200 Subject: [PATCH] R# cleanup og bedre datosjekk for sertifikater --- .../CertificateChainValidatorTests.cs | 8 +- .../CertificateValidatorTests.cs | 2 +- .../Security/SignedXmlWithAgnosticIdTests.cs | 79 +++++++++---------- .../SertifikatUtility.cs | 1 - .../Testdata/Transportkvittering.cs | 2 +- .../Utilities/CertificateChainUtilityTests.cs | 7 +- .../Validation/TestGenerator.cs | 36 ++++----- .../Validation/ValidationMessagesTests.cs | 8 +- .../Validation/XmlValidationRunnerTests.cs | 3 - .../Validation/XmlValidatorTests.cs | 64 ++++++++------- .../CertificateChainValidator.cs | 16 ++-- Difi.Felles.Utility/CertificateValidator.cs | 8 +- .../Properties/AssemblyInfo.cs | 1 - .../Security/SignedXmlWithAgnosticId.cs | 10 +-- .../Validation/ValidationMessages.cs | 4 +- .../Validation/XmlValidationRunner.cs | 4 +- SharedAssemblyInfo.cs | 1 - 17 files changed, 115 insertions(+), 139 deletions(-) diff --git a/Difi.Felles.Utility.Tester/CertificateChainValidatorTests.cs b/Difi.Felles.Utility.Tester/CertificateChainValidatorTests.cs index 242eb5f..73b5418 100755 --- a/Difi.Felles.Utility.Tester/CertificateChainValidatorTests.cs +++ b/Difi.Felles.Utility.Tester/CertificateChainValidatorTests.cs @@ -8,14 +8,14 @@ namespace Difi.Felles.Utility.Tester public class CertificateChainValidatorTests { - public class ValidateCertificateChain : CertificateChainValidatorTests + public class ValidateCertificateChainMethod : CertificateChainValidatorTests { [Fact] public void Valid_with_correct_root_and_intermediate() { //Arrange var productionCertificate = SertifikatUtility.GetProduksjonsMottakerSertifikatOppslagstjenesten(); - var certificateChainValidator = new CertificateChainValidator(CertificateChainUtility.ProduksjonsSertifikater()); + var certificateChainValidator = new CertificateChainValidator(CertificateChainUtility.ProductionCertificates()); //Act var result = certificateChainValidator.Validate(productionCertificate); @@ -32,7 +32,7 @@ public void Fails_with_wrong_root_and_intermediate() var productionCertificate = SertifikatUtility.GetProduksjonsMottakerSertifikatOppslagstjenesten(); //Act - var certificateChainValidator = new CertificateChainValidator(CertificateChainUtility.FunksjoneltTestmiljøSertifikater()); + var certificateChainValidator = new CertificateChainValidator(CertificateChainUtility.TestCertificates()); var result = certificateChainValidator.Validate(productionCertificate); //Assert @@ -46,7 +46,7 @@ public void Fails_with_self_signed_certificate() { //Arrange var selfSignedCertificate = SertifikatUtility.GetEnhetstesterSelvsignertSertifikat(); - var certificateChainValidator = new CertificateChainValidator(CertificateChainUtility.ProduksjonsSertifikater()); + var certificateChainValidator = new CertificateChainValidator(CertificateChainUtility.ProductionCertificates()); //Act var result = certificateChainValidator.Validate(selfSignedCertificate); diff --git a/Difi.Felles.Utility.Tester/CertificateValidatorTests.cs b/Difi.Felles.Utility.Tester/CertificateValidatorTests.cs index 8b28c4d..4bc8f79 100755 --- a/Difi.Felles.Utility.Tester/CertificateValidatorTests.cs +++ b/Difi.Felles.Utility.Tester/CertificateValidatorTests.cs @@ -6,7 +6,7 @@ namespace Difi.Felles.Utility.Tester public class CertificateValidatorTests { - public class ValidateCertificateAndChain : CertificateValidatorTests + public class ValidateCertificateAndChainMethod : CertificateValidatorTests { [Fact] public void Returns_fail_if_certificate_error() diff --git a/Difi.Felles.Utility.Tester/Security/SignedXmlWithAgnosticIdTests.cs b/Difi.Felles.Utility.Tester/Security/SignedXmlWithAgnosticIdTests.cs index ef7ae59..34a4d68 100755 --- a/Difi.Felles.Utility.Tester/Security/SignedXmlWithAgnosticIdTests.cs +++ b/Difi.Felles.Utility.Tester/Security/SignedXmlWithAgnosticIdTests.cs @@ -11,28 +11,33 @@ using Difi.Felles.Utility.Utilities; using Xunit; - namespace Difi.Felles.Utility.Tester.Security { - public class SignedXmlWithAgnosticIdTests { - public class KonstruktørMethod : SignedXmlWithAgnosticIdTests { [Fact] - public void KonstruktørMedXmlDokumentOgSertifikat() + public void FeilerMedPrivatnøkkelSomIkkeErRsaIKKEIMPLEMENTERT() { - //Arrange - var xmlDokument = XmlUtility.ToXmlDocument(TransportKvittering.TransportOkKvittertingFunksjoneltTestmiljø); - var sertifikat = CertificateUtility.GetAvsenderEnhetstesterSertifikat(); - var signedXmlWithAgnosticId = new SignedXmlWithAgnosticId(xmlDokument, sertifikat); + //Denne testen er ikke skrevet fordi vi ikke har klart å lage et sertifikat som bruker + //DSACryptoProvider. Script `GenererSertifikatScripts.txt` inneholder info om hvordan. + //Feilmelding `bad data` kommer, så noe er galt. Jeg mener det likevel er viktig å påpeke + //at vi bør ha testdekning på dette. Kanskje kan fremtiden løse dette problemet? + // Aleksander 02.11.2015 - //Act - var signingKey = signedXmlWithAgnosticId.SigningKey; + ////////////////////////////////////////////// + //P12 container med privatekey og sertifikat som holder i 10 år, DSA kryptering + ////////////////////////////////////////////// - //Assert - Assert.True(signingKey is RSACryptoServiceProvider); + //Lag dsa-parametere + // openssl dsaparam -out dsap.pem 2048 + + //Lag privatnøkkel og sertifikat + //openssl req -x509 - newkey dsa: dsap.pem - keyout key.pem -out certificate.pem - days 3650 - nodes - subj "/C=NO/ST=Oslo/L=Posthuset/O=Digipost testsertifikat Name/OU=Org/CN=www.digiphoest.no" + + //Pakk inn i container + //openssl pkcs12 -export -out certificate.pfx - inkey key.pem -in certificate.pem } [Fact] @@ -55,30 +60,21 @@ public void FeilerMedSertifikatUtenPrivatnøkkel() } [Fact] - public void FeilerMedPrivatnøkkelSomIkkeErRsaIKKEIMPLEMENTERT() + public void KonstruktørMedXmlDokumentOgSertifikat() { - //Denne testen er ikke skrevet fordi vi ikke har klart å lage et sertifikat som bruker - //DSACryptoProvider. Script `GenererSertifikatScripts.txt` inneholder info om hvordan. - //Feilmelding `bad data` kommer, så noe er galt. Jeg mener det likevel er viktig å påpeke - //at vi bør ha testdekning på dette. Kanskje kan fremtiden løse dette problemet? - // Aleksander 02.11.2015 - - ////////////////////////////////////////////// - //P12 container med privatekey og sertifikat som holder i 10 år, DSA kryptering - ////////////////////////////////////////////// - - //Lag dsa-parametere - // openssl dsaparam -out dsap.pem 2048 + //Arrange + var xmlDokument = XmlUtility.ToXmlDocument(TransportKvittering.TransportOkKvittertingFunksjoneltTestmiljø); + var sertifikat = CertificateUtility.GetAvsenderEnhetstesterSertifikat(); + var signedXmlWithAgnosticId = new SignedXmlWithAgnosticId(xmlDokument, sertifikat); - //Lag privatnøkkel og sertifikat - //openssl req -x509 - newkey dsa: dsap.pem - keyout key.pem -out certificate.pem - days 3650 - nodes - subj "/C=NO/ST=Oslo/L=Posthuset/O=Digipost testsertifikat Name/OU=Org/CN=www.digiphoest.no" + //Act + var signingKey = signedXmlWithAgnosticId.SigningKey; - //Pakk inn i container - //openssl pkcs12 -export -out certificate.pfx - inkey key.pem -in certificate.pem + //Assert + Assert.True(signingKey is RSACryptoServiceProvider); } } - public class FindIdElementMethod : SignedXmlWithAgnosticIdTests { [Fact] @@ -112,13 +108,12 @@ public void FinnerIdElementUansettSkrivemåte() Assert.NotNull(response); Assert.True( - response.Attributes.OfType().Any(a => a.LocalName == id && a.Value == "value")); + response.Attributes.OfType().Any(a => (a.LocalName == id) && (a.Value == "value"))); } } } } - public class GetPublicKeyMethod : SignedXmlWithAgnosticIdTests { private XmlNamespaceManager GetNamespaceManager(XmlDocument forDocument) @@ -151,18 +146,18 @@ private void AddBodySignatureNodeToSignedXmlWithAgnosticId(XmlDocument kildeXmlD private object GetPublicKey(SignedXmlWithAgnosticId signedXmlWithAgnosticId) { - return typeof (SignedXmlWithAgnosticId).GetMethod("GetPublicKey", BindingFlags.Instance | BindingFlags.NonPublic) + return typeof(SignedXmlWithAgnosticId).GetMethod("GetPublicKey", BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(signedXmlWithAgnosticId, null); } [Fact] - public void GetsKeyFromTransportReceipt() + public void GetsKeyFromMessageReceiptBody() { //Arrange - var xmlDokument = XmlUtility.ToXmlDocument(TransportKvittering.TransportOkKvittertingFunksjoneltTestmiljø); - var signedXmlWithAgnosticId = new SignedXmlWithAgnosticId(xmlDokument); + var document = XmlUtility.ToXmlDocument(ReceiptResponse.FunctionalTestEnvironment); + var signedXmlWithAgnosticId = new SignedXmlWithAgnosticId(document); - AddHeaderSignatureNodeToSignedXmlWithAgnosticId(xmlDokument, signedXmlWithAgnosticId); + AddBodySignatureNodeToSignedXmlWithAgnosticId(document, signedXmlWithAgnosticId); //Act var signingKey = GetPublicKey(signedXmlWithAgnosticId); @@ -192,13 +187,13 @@ public void GetsKeyFromMessageReceiptHeader() } [Fact] - public void GetsKeyFromMessageReceiptBody() + public void GetsKeyFromTransportReceipt() { //Arrange - var document = XmlUtility.ToXmlDocument(ReceiptResponse.FunctionalTestEnvironment); - var signedXmlWithAgnosticId = new SignedXmlWithAgnosticId(document); + var xmlDokument = XmlUtility.ToXmlDocument(TransportKvittering.TransportOkKvittertingFunksjoneltTestmiljø); + var signedXmlWithAgnosticId = new SignedXmlWithAgnosticId(xmlDokument); - AddBodySignatureNodeToSignedXmlWithAgnosticId(document, signedXmlWithAgnosticId); + AddHeaderSignatureNodeToSignedXmlWithAgnosticId(xmlDokument, signedXmlWithAgnosticId); //Act var signingKey = GetPublicKey(signedXmlWithAgnosticId); @@ -229,7 +224,7 @@ public void SignatureNodeAndBinarySecurityTokenAreAlike() var binarySecurityToken = doc.SelectSingleNode("//wsse:BinarySecurityToken", mgr); var key = new X509Certificate2(Convert.FromBase64String(binarySecurityToken.InnerText)); - var publicKey = typeof (SignedXmlWithAgnosticId).GetMethod("GetPublicKey", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(signedXmlWithAgnosticId, null) as AsymmetricAlgorithm; + var publicKey = typeof(SignedXmlWithAgnosticId).GetMethod("GetPublicKey", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(signedXmlWithAgnosticId, null) as AsymmetricAlgorithm; //Assert Assert.Equal(publicKey.ToXmlString(false), key.PublicKey.Key.ToXmlString(false)); diff --git a/Difi.Felles.Utility.Tester/SertifikatUtility.cs b/Difi.Felles.Utility.Tester/SertifikatUtility.cs index f05d0f6..2ab35ba 100755 --- a/Difi.Felles.Utility.Tester/SertifikatUtility.cs +++ b/Difi.Felles.Utility.Tester/SertifikatUtility.cs @@ -32,7 +32,6 @@ public static X509Certificate2 GetValidSelfSignedTestCertificate() return new X509Certificate2(ResourceUtility.ReadAllBytes(true, "Enhetstester", "ValidSelfSignedBringAs.cer")); } - public static X509Certificate2 TestIntegrasjonssertifikat() { return GetPostenCertificate(); diff --git a/Difi.Felles.Utility.Tester/Testdata/Transportkvittering.cs b/Difi.Felles.Utility.Tester/Testdata/Transportkvittering.cs index 1218d19..ebbe128 100755 --- a/Difi.Felles.Utility.Tester/Testdata/Transportkvittering.cs +++ b/Difi.Felles.Utility.Tester/Testdata/Transportkvittering.cs @@ -14,7 +14,7 @@ internal class TransportKvittering public static string TransportOkKvittertingFunksjoneltTestmiljøMedInput( string dokumentPakkeId = "4fa27c07-8a0f-45a9-954e-c658f6c480af@meldingsformidler.sdp.difi.no", string securityBinary = "MIIE7jCCA9agAwIBAgIKGBj1bv99Jpi+EzANBgkqhkiG9w0BAQsFADBRMQswCQYDVQQGEwJOTzEdMBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIzAhBgNVBAMMGkJ1eXBhc3MgQ2xhc3MgMyBUZXN0NCBDQSAzMB4XDTE0MDQyNDEyMzExMVoXDTE3MDQyNDIxNTkwMFowVTELMAkGA1UEBhMCTk8xGDAWBgNVBAoMD1BPU1RFTiBOT1JHRSBBUzEYMBYGA1UEAwwPUE9TVEVOIE5PUkdFIEFTMRIwEAYDVQQFEwk5ODQ2NjExODUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDLTnQryf2bmiyQ9q3ylQ6xMl7EhGIbjuziXkRTfL+M94m3ceAiko+r2piefKCiquLMK4j+UDcOapUtLC4dT4c6GhRH4FIOEn5aNS2I/njTenBypWka/VEhQUj7zvIh5G4UXIDIXYvLd7gideeMtkX24KUh2XVlh+PcqLGHirqBwVfFiTn5SKhr/ojhYYEb2xxTk3AY9nLd1MMffKQwUWmfoTos4scREYGI2R2vWxKWPcDqk+jig2DISWSJSuerz3HMYAAmp+Gjt0oFJNiyOFaFyGwT3DvqwOMQWwWXdmLh1NxMgTpghXAaXae76ucm9GDQ9E7ytf+JA096RWoi+5GtAgMBAAGjggHCMIIBvjAJBgNVHRMEAjAAMB8GA1UdIwQYMBaAFD+u9XgLkqNwIDVfWvr3JKBSAfBBMB0GA1UdDgQWBBTVyVLqcjWf1Qd0gsmCTrhXiWeqVDAOBgNVHQ8BAf8EBAMCBLAwFgYDVR0gBA8wDTALBglghEIBGgEAAwIwgbsGA1UdHwSBszCBsDA3oDWgM4YxaHR0cDovL2NybC50ZXN0NC5idXlwYXNzLm5vL2NybC9CUENsYXNzM1Q0Q0EzLmNybDB1oHOgcYZvbGRhcDovL2xkYXAudGVzdDQuYnV5cGFzcy5uby9kYz1CdXlwYXNzLGRjPU5PLENOPUJ1eXBhc3MlMjBDbGFzcyUyMDMlMjBUZXN0NCUyMENBJTIwMz9jZXJ0aWZpY2F0ZVJldm9jYXRpb25MaXN0MIGKBggrBgEFBQcBAQR+MHwwOwYIKwYBBQUHMAGGL2h0dHA6Ly9vY3NwLnRlc3Q0LmJ1eXBhc3Mubm8vb2NzcC9CUENsYXNzM1Q0Q0EzMD0GCCsGAQUFBzAChjFodHRwOi8vY3J0LnRlc3Q0LmJ1eXBhc3Mubm8vY3J0L0JQQ2xhc3MzVDRDQTMuY2VyMA0GCSqGSIb3DQEBCwUAA4IBAQCmMpAGaNplOgx3b4Qq6FLEcpnMOnPlSWBC7pQEDWx6OtNUHDm56fBoyVQYKR6LuGfalnnOKuB/sGSmO3eYlh7uDK9WA7bsNU/W8ZiwYwF6PBRui2rrqYk3kj4NLTNlyh/AOO1a2FDFHu369W0zcjj5ns7qs0K3peXtLX8pVxA8RmjwdGe69P/2r6s2A5CBj7oXZJD0Yo2dJFdsZzonT900sUi+MWzlhj3LxU5/684NWc2NI6ZPof/dyYpy3K/AFzpDLWGSmaDO66hPl7EfoJxEiX0DNBaQzNIyRFPh0ir0jM+32ZQ4goR8bAtyhKeTyA/4+Qx1WQXS3wURCC0lsbMh" - ) + ) { return $"{securityBinary}2015-10-22T14:27:47.188Z2015-10-22T14:32:47.188ZXryysQP3I8XTSL9icB3WCy17JxqqZIvNchNVzr9/rbc=PuFI7dA66+N5d4Cov7GAdXYQq3wKBe8FwGknZtH/s4E=XI9g0I9fGSf/NVJVxe43kKCgF0OFdTc3F9SXSkE5PxA=iHhXDHohEm9cFfqz6sLc5JTUULKmhqXqCNKqDA+LoJETaR7mLF6buwlSBX4cDms6BbfY//z1RRxM8g6bEfjZtaPGBoRUUH5ar4+jJX74NDoFa37CPN/YjLNYfx98Ld5Gidx/DljDlXQg3NTwYks8LXj1NyjTWC1bQGVFA4Gw7WC81GrUpRTP8fN/WhiN3hliZB3Q04K6KLFq1DH7aYxEvlYkziXBE7pYjdeFLmFGm+cVkVWG4j2t0GCJ8c75XIXHh1ZXhAUwKUHislP3gJ0z0Jmmvbcn6oLcSdCHJ1WYwGe5sxfPiGIbfKwYR3DsyqTTyOnXsqGP/S9vUndQ/bpQDQ==2015-10-22T16:27:47.187+02:00604d8104-d957-435c-a7ec-d5611f97f249388214db-29cc-43c7-9543-877e017e5bb45jQFrdmBGPCSWj5Sq4bVoYyfrF8vAYqKl1h3m/l1j5o=clCREk3SJj5Y+FZ9oD8cnlMg1SDR74d8rXNcZQQIl8A="; } diff --git a/Difi.Felles.Utility.Tester/Utilities/CertificateChainUtilityTests.cs b/Difi.Felles.Utility.Tester/Utilities/CertificateChainUtilityTests.cs index 0950a38..3b98fe3 100755 --- a/Difi.Felles.Utility.Tester/Utilities/CertificateChainUtilityTests.cs +++ b/Difi.Felles.Utility.Tester/Utilities/CertificateChainUtilityTests.cs @@ -4,10 +4,8 @@ namespace Difi.Felles.Utility.Tester.Utilities { - public class CertificateChainUtilityTests { - public class TestsertifikaterMethod : CertificateChainUtilityTests { [Fact] @@ -26,7 +24,6 @@ public void ReturnererFireSertifikaterMedThumbprint() } } - public class ProduksjonssertifikaterMethod : CertificateChainUtilityTests { [Fact] @@ -45,19 +42,17 @@ public void ReturnererFireSertifikaterMedThumbprint() } } - public class CertificateChainInfoTests : CertificateChainUtilityTests { [Fact] public void DebugMesages() { - int i = 0; + var i = 0; foreach (var certificate in CertificateChainUtility.TestCertificates()) { Trace.WriteLine($"{i++}: Issuer `{certificate.Issuer}`, thumbprint `{certificate.Thumbprint}`"); } } - } } } \ No newline at end of file diff --git a/Difi.Felles.Utility.Tester/Validation/TestGenerator.cs b/Difi.Felles.Utility.Tester/Validation/TestGenerator.cs index 6598b73..2b5fb7a 100755 --- a/Difi.Felles.Utility.Tester/Validation/TestGenerator.cs +++ b/Difi.Felles.Utility.Tester/Validation/TestGenerator.cs @@ -11,6 +11,13 @@ internal static class TestGenerator { private static readonly ResourceUtility ResourceUtility = new ResourceUtility("Difi.Felles.Utility.Tester.Testdata"); + public static XmlSchemaSet XmlSchemaSet() + { + var xmlSchemaSet = new XmlSchemaSet(); + xmlSchemaSet.Add("http://tempuri.org/po.xsd", XmlReader.Create(new MemoryStream(ResourceUtility.ReadAllBytes(true, "Xsd.Sample.xsd")))); + return xmlSchemaSet; + } + public interface ITestCouple { List ExpectedValidationMessages { get; } @@ -20,21 +27,16 @@ public interface ITestCouple public class ValidTestCouple : ITestCouple { + public List ExpectedValidationMessages => new List(); + public string Input() { return Encoding.UTF8.GetString(ResourceUtility.ReadAllBytes(true, "Xml.Valid.xml")); } - - public List ExpectedValidationMessages => new List(); } public class InvalidContentTestCouple : ITestCouple { - public string Input() - { - return Encoding.UTF8.GetString(ResourceUtility.ReadAllBytes(true, "Xml.InvalidIdentifikatorContent.xml")); - } - public List ExpectedValidationMessages { get @@ -44,15 +46,15 @@ public List ExpectedValidationMessages return new List {validationMessageEn, validationMessageNb}; } } - } - public class InvalidSyntaxTestCouple : ITestCouple - { public string Input() { - return Encoding.UTF8.GetString(ResourceUtility.ReadAllBytes(true, "Xml.UnknownElement.xml")); + return Encoding.UTF8.GetString(ResourceUtility.ReadAllBytes(true, "Xml.InvalidIdentifikatorContent.xml")); } + } + public class InvalidSyntaxTestCouple : ITestCouple + { public List ExpectedValidationMessages { get @@ -62,13 +64,11 @@ public List ExpectedValidationMessages return new List {validationMessageEn, validationMessageNb}; } } - } - public static XmlSchemaSet XmlSchemaSet() - { - var xmlSchemaSet = new XmlSchemaSet(); - xmlSchemaSet.Add("http://tempuri.org/po.xsd", XmlReader.Create(new MemoryStream(ResourceUtility.ReadAllBytes(true,"Xsd.Sample.xsd")))); - return xmlSchemaSet; - } + public string Input() + { + return Encoding.UTF8.GetString(ResourceUtility.ReadAllBytes(true, "Xml.UnknownElement.xml")); + } + } } } \ No newline at end of file diff --git a/Difi.Felles.Utility.Tester/Validation/ValidationMessagesTests.cs b/Difi.Felles.Utility.Tester/Validation/ValidationMessagesTests.cs index e6b076d..3dd35a3 100755 --- a/Difi.Felles.Utility.Tester/Validation/ValidationMessagesTests.cs +++ b/Difi.Felles.Utility.Tester/Validation/ValidationMessagesTests.cs @@ -1,14 +1,11 @@ -using System.Collections.Generic; -using System.Xml.Schema; +using System.Xml.Schema; using Difi.Felles.Utility.Validation; using Xunit; namespace Difi.Felles.Utility.Tester.Validation { - public class ValidationMessagesTests { - public class AddErrorMethod : ValidationMessagesTests { [Fact] @@ -26,7 +23,6 @@ public void ErrorMessageIsAdded() } } - public class AddWarningMethod : ValidationMessagesTests { [Fact] @@ -44,7 +40,6 @@ public void WarningMessageIsAdded() } } - public class ToStringMethod : ValidationMessagesTests { [Fact] @@ -58,6 +53,5 @@ public void OutputsCorrectly() Assert.Same(expectedError, messages.ToString()); } } - } } \ No newline at end of file diff --git a/Difi.Felles.Utility.Tester/Validation/XmlValidationRunnerTests.cs b/Difi.Felles.Utility.Tester/Validation/XmlValidationRunnerTests.cs index 45f20d2..f72ba91 100755 --- a/Difi.Felles.Utility.Tester/Validation/XmlValidationRunnerTests.cs +++ b/Difi.Felles.Utility.Tester/Validation/XmlValidationRunnerTests.cs @@ -3,10 +3,8 @@ namespace Difi.Felles.Utility.Tester.Validation { - public class XmlValidationRunnerTests { - public class ConstructorMethod : XmlValidationRunnerTests { [Fact] @@ -23,7 +21,6 @@ public void SimpleInitialization() } } - public class ValidateMethod : ValidationMessagesTests { [Fact] diff --git a/Difi.Felles.Utility.Tester/Validation/XmlValidatorTests.cs b/Difi.Felles.Utility.Tester/Validation/XmlValidatorTests.cs index bfb82a6..771f07e 100755 --- a/Difi.Felles.Utility.Tester/Validation/XmlValidatorTests.cs +++ b/Difi.Felles.Utility.Tester/Validation/XmlValidatorTests.cs @@ -3,22 +3,40 @@ namespace Difi.Felles.Utility.Tester.Validation { - public class XmlValidatorTests { - public class ValidateMethod : XmlValidatorTests { [Fact] - public void ValidateReturnsBoolAndOutsString() + public void MultipleValidateShouldNotHoldValidationState() + { + XmlValidator validator = new XmlValidatorTestImplementation(); + + var invalidContentTestCouple = new TestGenerator.InvalidContentTestCouple(); + List messagesList; + var validateResult = validator.Validate(invalidContentTestCouple.Input(), out messagesList); + Assert.False(validateResult); + Assert.True(invalidContentTestCouple.ExpectedValidationMessages.Contains(messagesList.ToString())); + + var validTestCouple = new TestGenerator.ValidTestCouple(); + validateResult = validator.Validate(validTestCouple.Input(), out messagesList); + Assert.True(validateResult); + Assert.Equal(0, messagesList.Count); + + var invalidSyntaxTestCouple = new TestGenerator.InvalidSyntaxTestCouple(); + validateResult = validator.Validate(invalidSyntaxTestCouple.Input(), out messagesList); + Assert.False(validateResult); + Assert.True(invalidSyntaxTestCouple.ExpectedValidationMessages.Contains(messagesList.ToString())); + } + + [Fact] + public void ValidateReturnsBool() { var invalidContentTestCouple = new TestGenerator.InvalidContentTestCouple(); XmlValidator validator = new XmlValidatorTestImplementation(); - string validationMessage; - - var status = validator.Validate(invalidContentTestCouple.Input(), out validationMessage); - Assert.True(invalidContentTestCouple.ExpectedValidationMessages.Contains(validationMessage)); + var status = validator.Validate(invalidContentTestCouple.Input()); + Assert.False(status); } @@ -28,7 +46,7 @@ public void ValidateReturnsBoolAndOutsListOfStrings() var invalidContentTestCouple = new TestGenerator.InvalidContentTestCouple(); XmlValidator validator = new XmlValidatorTestImplementation(); List validationMessages; - + var status = validator.Validate(invalidContentTestCouple.Input(), out validationMessages); Assert.True(invalidContentTestCouple.ExpectedValidationMessages.Contains(validationMessages.ToString())); @@ -36,13 +54,15 @@ public void ValidateReturnsBoolAndOutsListOfStrings() } [Fact] - public void ValidateReturnsBool() + public void ValidateReturnsBoolAndOutsString() { var invalidContentTestCouple = new TestGenerator.InvalidContentTestCouple(); XmlValidator validator = new XmlValidatorTestImplementation(); - - var status = validator.Validate(invalidContentTestCouple.Input()); + string validationMessage; + var status = validator.Validate(invalidContentTestCouple.Input(), out validationMessage); + + Assert.True(invalidContentTestCouple.ExpectedValidationMessages.Contains(validationMessage)); Assert.False(status); } @@ -83,28 +103,6 @@ public void ValidateWithInvalidSyntaxShouldReturnFalseAndGiveValidationError() Assert.True(invalidSyntaxTestRequest.ExpectedValidationMessages.Contains(messagesList.ToString())); Assert.False(validateResult); } - - [Fact] - public void MultipleValidateShouldNotHoldValidationState() - { - XmlValidator validator = new XmlValidatorTestImplementation(); - - var invalidContentTestCouple = new TestGenerator.InvalidContentTestCouple(); - List messagesList; - var validateResult = validator.Validate(invalidContentTestCouple.Input(), out messagesList); - Assert.False(validateResult); - Assert.True(invalidContentTestCouple.ExpectedValidationMessages.Contains(messagesList.ToString())); - - var validTestCouple = new TestGenerator.ValidTestCouple(); - validateResult = validator.Validate(validTestCouple.Input(), out messagesList); - Assert.True(validateResult); - Assert.Equal(0, messagesList.Count); - - var invalidSyntaxTestCouple = new TestGenerator.InvalidSyntaxTestCouple(); - validateResult = validator.Validate(invalidSyntaxTestCouple.Input(), out messagesList); - Assert.False(validateResult); - Assert.True(invalidSyntaxTestCouple.ExpectedValidationMessages.Contains(messagesList.ToString())); - } } } } \ No newline at end of file diff --git a/Difi.Felles.Utility/CertificateChainValidator.cs b/Difi.Felles.Utility/CertificateChainValidator.cs index e6e5449..7e17038 100755 --- a/Difi.Felles.Utility/CertificateChainValidator.cs +++ b/Difi.Felles.Utility/CertificateChainValidator.cs @@ -42,24 +42,24 @@ public bool IsValidChain(X509Certificate2 certificate) /// Validerer sertifikatkjeden til sertifikatet. Gjør dette ved å validere mot /// /// - /// Status på kjeden etter validering hvis validering feilet. + /// Status på kjeden etter validering hvis validering feilet. /// [Obsolete("Use IsValidChain instead.")] - public bool ErGyldigSertifikatkjede(X509Certificate2 certificate, out string detaljertFeilinformasjon) + public bool ErGyldigSertifikatkjede(X509Certificate2 certificate, out string detailedErrorInformation) { - return IsValidChain(certificate, out detaljertFeilinformasjon); + return IsValidChain(certificate, out detailedErrorInformation); } /// /// Validerer sertifikatkjeden til sertifikatet. Gjør dette ved å validere mot /// /// - /// Status på kjeden etter validering hvis validering feilet. + /// Status på kjeden etter validering hvis validering feilet. /// - public bool IsValidChain(X509Certificate2 certificate, out string detaljertFeilinformasjon) + public bool IsValidChain(X509Certificate2 certificate, out string detailedErrorInformation) { var result = Validate(certificate); - detaljertFeilinformasjon = result.Message; + detailedErrorInformation = result.Message; return result.Type == CertificateValidationType.Valid; } @@ -132,10 +132,10 @@ private CertificateValidationResult ValidateThatUsingOnlyValidatorCertificates(X return ValidResult(certificate); } - private static CertificateValidationResult UsedExternalCertificatesResult(X509Certificate2 sertifikat, string chainAsString, string validatorCertificatesAsString) + private static CertificateValidationResult UsedExternalCertificatesResult(X509Certificate2 certificate, string chainAsString, string validatorCertificatesAsString) { return new CertificateValidationResult(CertificateValidationType.InvalidChain, - $"Validering av '{sertifikat.ToShortString()}' feilet. {Environment.NewLine}" + + $"Validering av '{certificate.ToShortString()}' feilet. {Environment.NewLine}" + $"Dette skjer fordi kjeden ble bygd med følgende sertifikater: {Environment.NewLine}{chainAsString}, " + $"men kun følgende er godkjent for å bygge kjeden: {Environment.NewLine}{validatorCertificatesAsString}. Dette skjer som oftest om sertifikater blir hentet fra Certificate Store på Windows, " + "og det tillates ikke under validering. Det er kun gyldig å bygge en kjede med de sertifikatene sendt inn til validatoren."); diff --git a/Difi.Felles.Utility/CertificateValidator.cs b/Difi.Felles.Utility/CertificateValidator.cs index 26d566b..ca9df28 100755 --- a/Difi.Felles.Utility/CertificateValidator.cs +++ b/Difi.Felles.Utility/CertificateValidator.cs @@ -87,14 +87,14 @@ private static bool IsIssuedToOrganizationNumber(X509Certificate certificate, st return certificate.Subject.Contains($"SERIALNUMBER={certificateOrganizationNumber}") || certificate.Subject.Contains($"CN={certificateOrganizationNumber}"); } - private static bool IsActivatedCertificate(X509Certificate certificate) + private static bool IsActivatedCertificate(X509Certificate2 certificate) { - return DateTime.Now > DateTime.Parse(certificate.GetEffectiveDateString()); + return DateTime.Now > certificate.NotBefore; } - private static bool IsExpiredCertificate(X509Certificate certificate) + private static bool IsExpiredCertificate(X509Certificate2 certificate) { - return DateTime.Now > DateTime.Parse(certificate.GetExpirationDateString()); + return DateTime.Now > certificate.NotAfter; } } } \ No newline at end of file diff --git a/Difi.Felles.Utility/Properties/AssemblyInfo.cs b/Difi.Felles.Utility/Properties/AssemblyInfo.cs index c4d9483..36de275 100755 --- a/Difi.Felles.Utility/Properties/AssemblyInfo.cs +++ b/Difi.Felles.Utility/Properties/AssemblyInfo.cs @@ -4,5 +4,4 @@ [assembly: AssemblyTitle("Difi.Felles.Utility")] [assembly: ComVisible(false)] - [assembly: InternalsVisibleTo("Difi.Oppslagstjeneste.Klient.Tester,PublicKey=00240000048000009400000006020000002400005253413100040000010001008b3388f9c416425f0145bbcf26e66b9a87c4e08b4cd41563e4bc8846df38ba4d997c5408cc77da26d79b03c39874a6af9df0aff3e7bdb3c0e53a91f6d19c50e160f5bf67986a04f0f985eca0252f557ed9ae520dd51e3107d6168d073d4ec5ada28d34e492ad9fb7af29c82309c5c0124211e679caea38d5463d2af9042dafda")] \ No newline at end of file diff --git a/Difi.Felles.Utility/Security/SignedXmlWithAgnosticId.cs b/Difi.Felles.Utility/Security/SignedXmlWithAgnosticId.cs index 561c1aa..78cda51 100755 --- a/Difi.Felles.Utility/Security/SignedXmlWithAgnosticId.cs +++ b/Difi.Felles.Utility/Security/SignedXmlWithAgnosticId.cs @@ -47,7 +47,7 @@ public SignedXmlWithAgnosticId(XmlDocument xmlDocument, X509Certificate2 certifi // Adds signature method to crypto api if (CryptoConfig.CreateFromName(signatureMethod) == null) - CryptoConfig.AddAlgorithm(typeof (RsaPkCs1Sha256SignatureDescription), signatureMethod); + CryptoConfig.AddAlgorithm(typeof(RsaPkCs1Sha256SignatureDescription), signatureMethod); // Makes sure the signingkey is using Microsoft Enhanced RSA and AES Cryptographic Provider which enables SHA256 if (!certificate.HasPrivateKey) @@ -90,11 +90,11 @@ public override XmlElement GetIdElement(XmlDocument doc, string id) // Check to se if id element is within the signatures object node. This is used by ESIs Xml Advanced Electronic Signatures (Xades) if (idElem == null) { - if (Signature != null && Signature.ObjectList != null) + if ((Signature != null) && (Signature.ObjectList != null)) { foreach (DataObject dataObject in Signature.ObjectList) { - if (dataObject.Data != null && dataObject.Data.Count > 0) + if ((dataObject.Data != null) && (dataObject.Data.Count > 0)) { foreach (XmlNode dataNode in dataObject.Data) { @@ -145,7 +145,7 @@ private AsymmetricAlgorithm GetNextKey() GetPublicKeysAndSetEnumerator(); } - while (_publicKeyListEnumerator != null && _publicKeyListEnumerator.MoveNext()) + while ((_publicKeyListEnumerator != null) && _publicKeyListEnumerator.MoveNext()) { publicKey = _publicKeyListEnumerator.Current; } @@ -191,7 +191,7 @@ private X509Certificate2 GetBinarySecurityToken(XmlNode securityTokenReference) X509Certificate2 publicCertificate = null; var keyElement = FindIdElement(_xmlDokument, securityTokenReferenceUri); - if (keyElement != null && !string.IsNullOrEmpty(keyElement.InnerText)) + if ((keyElement != null) && !string.IsNullOrEmpty(keyElement.InnerText)) { publicCertificate = new X509Certificate2(Convert.FromBase64String(keyElement.InnerText)); } diff --git a/Difi.Felles.Utility/Validation/ValidationMessages.cs b/Difi.Felles.Utility/Validation/ValidationMessages.cs index db152da..7f18a02 100755 --- a/Difi.Felles.Utility/Validation/ValidationMessages.cs +++ b/Difi.Felles.Utility/Validation/ValidationMessages.cs @@ -7,9 +7,9 @@ namespace Difi.Felles.Utility.Validation { public class ValidationMessages : List { - public bool HasErrors { get; private set; } = false; + public bool HasErrors { get; private set; } - public bool HasWarnings { get; private set; } = false; + public bool HasWarnings { get; private set; } internal void Add(XmlSeverityType severity, string message) { diff --git a/Difi.Felles.Utility/Validation/XmlValidationRunner.cs b/Difi.Felles.Utility/Validation/XmlValidationRunner.cs index 04ce616..31a6314 100755 --- a/Difi.Felles.Utility/Validation/XmlValidationRunner.cs +++ b/Difi.Felles.Utility/Validation/XmlValidationRunner.cs @@ -15,13 +15,13 @@ internal class XmlValidationRunner internal static readonly List ToleratedErrors = new List {ToleratedXsdIdErrorEnUs, ToleratedXsdIdErrorNbNo, ToleratedPrefixListErrorEnUs, ToleratedPrefixListErrorNbNo}; - internal XmlSchemaSet XmlSchemaSet { get; } - internal XmlValidationRunner(XmlSchemaSet xmlSchemaSet) { XmlSchemaSet = xmlSchemaSet; } + internal XmlSchemaSet XmlSchemaSet { get; } + internal ValidationMessages ValidationMessages { get; } = new ValidationMessages(); internal bool Validate(string document) diff --git a/SharedAssemblyInfo.cs b/SharedAssemblyInfo.cs index 5a73eff..309bffb 100755 --- a/SharedAssemblyInfo.cs +++ b/SharedAssemblyInfo.cs @@ -9,5 +9,4 @@ [assembly: AssemblyFileVersion("0.8.0.*")] [assembly: AssemblyCopyright("© 2015-2016 Direktoratet for forvaltning og IKT (Difi)")] [assembly: AssemblyCulture("")] - [assembly: InternalsVisibleTo("Difi.Felles.Utility.Tester,PublicKey=00240000048000009400000006020000002400005253413100040000010001008b3388f9c416425f0145bbcf26e66b9a87c4e08b4cd41563e4bc8846df38ba4d997c5408cc77da26d79b03c39874a6af9df0aff3e7bdb3c0e53a91f6d19c50e160f5bf67986a04f0f985eca0252f557ed9ae520dd51e3107d6168d073d4ec5ada28d34e492ad9fb7af29c82309c5c0124211e679caea38d5463d2af9042dafda")] \ No newline at end of file