public void Rfc3161TimestampProvider_Failure_Cancelled() { // Arrange var logger = new TestLogger(); var timestampProvider = new Rfc3161TimestampProvider(new Uri(_testTimestampServer)); var data = "Test data to be signed and timestamped"; using (var authorCert = new X509Certificate2(_trustedTestCert.Source.Cert)) { var signedCms = SigningTestUtility.GenerateSignedCms(authorCert, Encoding.ASCII.GetBytes(data)); var signatureValue = signedCms.Encode(); var request = new TimestampRequest { Certificate = authorCert, SigningSpec = SigningSpecifications.V1, TimestampHashAlgorithm = Common.HashAlgorithmName.SHA256, SignatureValue = signatureValue }; // Act Action timestampAction = () => timestampProvider.TimestampData(request, logger, new CancellationToken(canceled: true)); // Assert timestampAction.ShouldThrow <OperationCanceledException>() .WithMessage(_operationCancelledExceptionMessage); } }
private void VerifyTimestampData( ISigningTestServer testServer, TimestampService timestampService, Action <Rfc3161TimestampProvider, TimestampRequest> verifyTimestampData) { using (testServer.RegisterResponder(timestampService)) { var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); using (var certificate = new X509Certificate2(_trustedTestCert.Source.Cert)) { var timestampHashAlgorithm = Common.HashAlgorithmName.SHA256; var content = new SignatureContent(SigningSpecifications.V1, Common.HashAlgorithmName.SHA256, "peach"); var signedCms = SigningTestUtility.GenerateSignedCms(certificate, content.GetBytes()); var signature = PrimarySignature.Load(signedCms.Encode()); var signatureValue = signature.GetSignatureValue(); var messageHash = timestampHashAlgorithm.ComputeHash(signatureValue); var request = new TimestampRequest( SigningSpecifications.V1, messageHash, timestampHashAlgorithm, SignaturePlacement.PrimarySignature); verifyTimestampData(timestampProvider, request); } } }
public async Task <byte[]> GenerateSignedPackageBytesAsync( Stream inputPackageStream, SignPackageRequest request, Uri timestampUri, ITestOutputHelper output) { var testLogger = new TestLogger(output); var timestampProvider = new Rfc3161TimestampProvider(timestampUri); var signatureProvider = new X509SignatureProvider(timestampProvider); using (var outputPackageStream = new MemoryStream()) { await SigningUtility.SignAsync( new SigningOptions( inputPackageStream : new Lazy <Stream>(() => inputPackageStream), outputPackageStream : new Lazy <Stream>(() => outputPackageStream), overwrite : true, signatureProvider : signatureProvider, logger : testLogger), request, CancellationToken.None); return(outputPackageStream.ToArray()); } }
public async Task TimestampData_WhenRequestNull_Throws() { var logger = new TestLogger(); var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var authorCertName = "*****@*****.**"; var data = "Test data to be signed and timestamped"; Action <X509V3CertificateGenerator> modifyGenerator = delegate(X509V3CertificateGenerator gen) { gen.SetNotBefore(DateTime.MinValue); gen.SetNotBefore(DateTime.UtcNow.Subtract(TimeSpan.FromDays(1))); // cert has expired }; using (var authorCert = SigningTestUtility.GenerateCertificate(authorCertName, modifyGenerator: modifyGenerator)) { var signedCms = SigningTestUtility.GenerateSignedCms(authorCert, Encoding.ASCII.GetBytes(data)); var signatureValue = signedCms.Encode(); var request = new TimestampRequest { SigningSpec = SigningSpecifications.V1, TimestampHashAlgorithm = Common.HashAlgorithmName.SHA256, Signature = signatureValue }; // Act Action timestampAction = () => timestampProvider.TimestampData(null, logger, CancellationToken.None); // Assert timestampAction.ShouldThrow <ArgumentNullException>() .WithMessage(string.Format(_argumentNullExceptionMessage, nameof(request))); } }
public async Task TimestampData_WhenCancelled_Throws() { var logger = new TestLogger(); var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var data = "Test data to be signed and timestamped"; using (var authorCert = new X509Certificate2(_trustedTestCert.Source.Cert)) { var signedCms = SigningTestUtility.GenerateSignedCms(authorCert, Encoding.ASCII.GetBytes(data)); var signatureValue = signedCms.Encode(); var request = new TimestampRequest { SigningSpec = SigningSpecifications.V1, TimestampHashAlgorithm = Common.HashAlgorithmName.SHA256, Signature = signatureValue }; // Act Action timestampAction = () => timestampProvider.TimestampData(request, logger, new CancellationToken(canceled: true)); // Assert timestampAction.ShouldThrow <OperationCanceledException>() .WithMessage(_operationCancelledExceptionMessage); } }
public async Task GetTimestamp_WithValidInput_ReturnsTimestamp() { var logger = new TestLogger(); var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var content = new SignatureContent(SigningSpecifications.V1, Common.HashAlgorithmName.SHA256, "Test data to be signed and timestamped"); using (var authorCert = new X509Certificate2(_trustedTestCert.Source.Cert)) { var signedCms = SigningTestUtility.GenerateSignedCms(authorCert, content.GetBytes()); var primarySignature = PrimarySignature.Load(signedCms.Encode()); var timestampHashAlgorithm = Common.HashAlgorithmName.SHA256; var signatureValue = primarySignature.GetSignatureValue(); var messageHash = timestampHashAlgorithm.ComputeHash(signatureValue); var request = new TimestampRequest( signingSpecifications: SigningSpecifications.V1, hashedMessage: messageHash, hashAlgorithm: timestampHashAlgorithm, target: SignaturePlacement.PrimarySignature ); // Act var timestampedCms = timestampProvider.GetTimestamp(request, logger, CancellationToken.None); // Assert timestampedCms.Should().NotBeNull(); timestampedCms.Detached.Should().BeFalse(); timestampedCms.ContentInfo.Should().NotBeNull(); timestampedCms.SignerInfos.Count.Should().Be(1); } }
public async Task Timestamps_WithTwoAttributesAndOneValueEach_ReturnsTwoTimestamps() { var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var nupkg = new SimpleTestPackageContext(); using (var packageStream = await nupkg.CreateAsStreamAsync()) using (var testCertificate = new X509Certificate2(_testFixture.TrustedTestCertificate.Source.Cert)) { AuthorPrimarySignature authorSignature = await SignedArchiveTestUtility.CreateAuthorSignatureForPackageAsync( testCertificate, packageStream, timestampProvider); SignedCms updatedSignedCms = ModifyUnsignedAttributes(authorSignature.SignedCms, attributeTable => { BcAttribute attribute = attributeTable[PkcsObjectIdentifiers.IdAASignatureTimeStampToken]; Asn1Encodable value = attribute.AttrValues.ToArray().Single(); AttributeTable updatedAttributes = attributeTable.Add(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, value); return(updatedAttributes); }); AssertTimestampAttributeAndValueCounts(updatedSignedCms, expectedAttributesCount: 2, expectedValuesCount: 2); var updatedAuthorSignature = new AuthorPrimarySignature(updatedSignedCms); Assert.Equal(2, updatedAuthorSignature.Timestamps.Count); } }
public async Task GetTimestamp_WhenCancelled_Throws() { var logger = new TestLogger(); var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var content = new SignatureContent(SigningSpecifications.V1, Common.HashAlgorithmName.SHA256, "Test data to be signed and timestamped"); using (var authorCert = new X509Certificate2(_trustedTestCert.Source.Cert)) { var timestampHashAlgorithm = Common.HashAlgorithmName.SHA256; var signedCms = SigningTestUtility.GenerateSignedCms(authorCert, content.GetBytes()); var signature = PrimarySignature.Load(signedCms.Encode()); var signatureValue = signature.GetSignatureValue(); var messageHash = timestampHashAlgorithm.ComputeHash(signatureValue); var request = new TimestampRequest( signingSpecifications: SigningSpecifications.V1, hashedMessage: messageHash, hashAlgorithm: timestampHashAlgorithm, target: SignaturePlacement.PrimarySignature ); // Act Action timestampAction = () => timestampProvider.GetTimestamp(request, logger, new CancellationToken(canceled: true)); // Assert timestampAction.ShouldThrow <OperationCanceledException>() .WithMessage(_operationCancelledExceptionMessage); } }
public async Task GetTimestampAsync_WhenLoggerNull_ThrowsAsync() { var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var content = new SignatureContent(SigningSpecifications.V1, Common.HashAlgorithmName.SHA256, "Test data to be signed and timestamped"); using (var authorCert = new X509Certificate2(_trustedTestCert.Source.Cert)) { var timestampHashAlgorithm = Common.HashAlgorithmName.SHA256; var signedCms = SigningTestUtility.GenerateSignedCms(authorCert, content.GetBytes()); var signature = PrimarySignature.Load(signedCms.Encode()); var signatureValue = signature.GetSignatureValue(); var messageHash = timestampHashAlgorithm.ComputeHash(signatureValue); var request = new TimestampRequest( signingSpecifications: SigningSpecifications.V1, hashedMessage: messageHash, hashAlgorithm: timestampHashAlgorithm, target: SignaturePlacement.PrimarySignature ); // Assert var exception = await Assert.ThrowsAsync <ArgumentNullException>( () => timestampProvider.GetTimestampAsync(request, logger: null, CancellationToken.None)); Assert.Equal("logger", exception.ParamName); Assert.StartsWith("Value cannot be null.", exception.Message); } }
private void VerifyTimestampData( ISigningTestServer testServer, TimestampService timestampService, Action <Rfc3161TimestampProvider, TimestampRequest> verifyTimestampData) { using (testServer.RegisterResponder(timestampService)) { var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); using (var certificate = new X509Certificate2(_trustedTestCert.Source.Cert)) { var content = Encoding.UTF8.GetBytes("peach"); var signedCms = SigningTestUtility.GenerateSignedCms(certificate, content); var request = new TimestampRequest() { SigningSpec = SigningSpecifications.V1, TimestampHashAlgorithm = Common.HashAlgorithmName.SHA256, Signature = signedCms.Encode() }; verifyTimestampData(timestampProvider, request); } } }
public async Task TimestampData_WithValidInput_ReturnsTimestamp() { var logger = new TestLogger(); var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var data = "Test data to be signed and timestamped"; using (var authorCert = new X509Certificate2(_trustedTestCert.Source.Cert)) { var signedCms = SigningTestUtility.GenerateSignedCms(authorCert, Encoding.ASCII.GetBytes(data)); var signatureValue = signedCms.Encode(); var request = new TimestampRequest { SigningSpec = SigningSpecifications.V1, TimestampHashAlgorithm = Common.HashAlgorithmName.SHA256, Signature = signatureValue }; // Act var timestampedData = timestampProvider.TimestampData(request, logger, CancellationToken.None); var timestampedCms = new SignedCms(); timestampedCms.Decode(timestampedData); // Assert timestampedData.Should().NotBeNull(); timestampedCms.Should().NotBeNull(); timestampedCms.Detached.Should().BeFalse(); timestampedCms.ContentInfo.Should().NotBeNull(); timestampedCms.SignerInfos.Count.Should().Be(1); timestampedCms.SignerInfos[0].UnsignedAttributes.Count.Should().Be(1); timestampedCms.SignerInfos[0].UnsignedAttributes[0].Oid.Value.Should().Be(Oids.SignatureTimeStampTokenAttribute); } }
public async Task GetTimestampAsync_AssertCompleteChain_SuccessAsync() { var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var nupkg = new SimpleTestPackageContext(); using (var authorCert = new X509Certificate2(_trustedTestCert.Source.Cert)) using (var packageStream = await nupkg.CreateAsStreamAsync()) { // Act AuthorPrimarySignature signature = await SignedArchiveTestUtility.CreateAuthorSignatureForPackageAsync(authorCert, packageStream, timestampProvider); var authorSignedCms = signature.SignedCms; var timestamp = signature.Timestamps.First(); var timestampCms = timestamp.SignedCms; IX509CertificateChain certificateChain; var chainBuildSuccess = true; // rebuild the chain to get the list of certificates using (var chainHolder = new X509ChainHolder()) { var chain = chainHolder.Chain; var policy = chain.ChainPolicy; policy.ApplicationPolicy.Add(new Oid(Oids.TimeStampingEku)); policy.VerificationFlags = X509VerificationFlags.IgnoreNotTimeValid; policy.RevocationFlag = X509RevocationFlag.ExcludeRoot; policy.RevocationMode = X509RevocationMode.Online; var timestampSignerCertificate = timestampCms.SignerInfos[0].Certificate; chainBuildSuccess = chain.Build(timestampSignerCertificate); certificateChain = CertificateChainUtility.GetCertificateChain(chain); } using (certificateChain) { // Assert authorSignedCms.Should().NotBeNull(); authorSignedCms.Detached.Should().BeFalse(); authorSignedCms.ContentInfo.Should().NotBeNull(); authorSignedCms.SignerInfos.Count.Should().Be(1); authorSignedCms.SignerInfos[0].UnsignedAttributes.Count.Should().Be(1); authorSignedCms.SignerInfos[0].UnsignedAttributes[0].Oid.Value.Should().Be(Oids.SignatureTimeStampTokenAttribute); timestampCms.Should().NotBeNull(); timestampCms.Detached.Should().BeFalse(); timestampCms.ContentInfo.Should().NotBeNull(); chainBuildSuccess.Should().BeTrue(); certificateChain.Count.Should().Be(timestampCms.Certificates.Count); foreach (var cert in certificateChain) { timestampCms.Certificates.Contains(cert).Should().BeTrue(); } } } }
private static ISignatureProvider GetSignatureProvider(string timestamper) { Rfc3161TimestampProvider timestampProvider = null; if (!string.IsNullOrEmpty(timestamper)) { timestampProvider = new Rfc3161TimestampProvider(new Uri(timestamper)); } return(new X509SignatureProvider(timestampProvider)); }
public async Task Timestamp_Verify_WithOfflineRevocation_ReturnsCorrectFlagsAndLogsAsync() { var nupkg = new SimpleTestPackageContext(); using (var testServer = await SigningTestServer.CreateAsync()) using (var responders = new DisposableList <IDisposable>()) using (var packageStream = await nupkg.CreateAsStreamAsync()) using (var testCertificate = new X509Certificate2(_trustedTestCert.Source.Cert)) { var ca = CreateOfflineRevocationCA(testServer, responders); var timestampService = TimestampService.Create(ca); responders.Add(testServer.RegisterResponder(timestampService)); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var signature = await SignedArchiveTestUtility.CreateAuthorSignatureForPackageAsync(testCertificate, packageStream, timestampProvider); var timestamp = signature.Timestamps.First(); var settings = new SignedPackageVerifierSettings( allowUnsigned: false, allowUntrusted: false, allowIllegal: false, allowIgnoreTimestamp: false, allowMultipleTimestamps: false, allowNoTimestamp: false, allowUnknownRevocation: false, reportUnknownRevocation: true, verificationTarget: VerificationTarget.All, signaturePlacement: SignaturePlacement.Any, repositoryCountersignatureVerificationBehavior: SignatureVerificationBehavior.Always, revocationMode: RevocationMode.Online); var logs = new List <SignatureLog>(); var result = timestamp.Verify(signature, settings, HashAlgorithmName.SHA256, logs); result.HasFlag(SignatureVerificationStatusFlags.UnknownRevocation).Should().BeTrue(); var errors = logs.Where(l => l.Level == LogLevel.Error); errors.Count().Should().Be(RuntimeEnvironmentHelper.IsWindows ? 2 : 1); if (RuntimeEnvironmentHelper.IsWindows) { errors.Should().Contain(w => w.Code == NuGetLogCode.NU3028 && w.Message.Contains("The revocation function was unable to check revocation because the revocation server could not be reached.")); errors.Should().Contain(w => w.Code == NuGetLogCode.NU3028 && w.Message.Contains("The revocation function was unable to check revocation for the certificate.")); } else { errors.Should().Contain(w => w.Code == NuGetLogCode.NU3028 && w.Message.Contains("unable to get certificate CRL")); } } }
public async Task TimestampSignatureAsync_TimestampingCountersignature_Succeeds() { var logger = new TestLogger(); var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var signatureContent = new SignatureContent(SigningSpecifications.V1, Common.HashAlgorithmName.SHA256, "Test data to be signed and timestamped"); using (var authorCert = new X509Certificate2(_trustedTestCert.Source.Cert)) { var timestampHashAlgorithm = Common.HashAlgorithmName.SHA256; var signedCms = SigningTestUtility.GenerateRepositoryCountersignedSignedCms(authorCert, signatureContent.GetBytes()); var signature = PrimarySignature.Load(signedCms.Encode()); var signatureValue = signature.GetSignatureValue(); var messageHash = timestampHashAlgorithm.ComputeHash(signatureValue); var request = new TimestampRequest( SigningSpecifications.V1, messageHash, timestampHashAlgorithm, SignaturePlacement.Countersignature); // Act var primarySignature = await timestampProvider.TimestampSignatureAsync(signature, request, logger, CancellationToken.None); var repositoryCountersignature = RepositoryCountersignature.GetRepositoryCountersignature(primarySignature); // Assert repositoryCountersignature.Should().NotBeNull(); repositoryCountersignature.SignerInfo.Should().NotBeNull(); repositoryCountersignature.SignerInfo.UnsignedAttributes.Count.Should().BeGreaterOrEqualTo(1); var hasTimestampUnsignedAttribute = false; var timestampCms = new SignedCms(); foreach (var attr in repositoryCountersignature.SignerInfo.UnsignedAttributes) { if (string.Compare(attr.Oid.Value, Oids.SignatureTimeStampTokenAttribute, CultureInfo.CurrentCulture, CompareOptions.Ordinal) == 0) { hasTimestampUnsignedAttribute = true; timestampCms.Decode(attr.Values[0].RawData); } } hasTimestampUnsignedAttribute.Should().BeTrue(); timestampCms.CheckSignature(verifySignatureOnly: true); } }
public async Task GetTrustResultAsync_SettingsRequireExactlyOneTimestamp_MultipleTimestamps_Fails() { // Arrange var nupkg = new SimpleTestPackageContext(); var testLogger = new TestLogger(); var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var setting = new SignedPackageVerifierSettings( allowUnsigned: false, allowIllegal: false, allowUntrusted: false, allowUntrustedSelfIssuedCertificate: false, allowIgnoreTimestamp: false, allowMultipleTimestamps: false, allowNoTimestamp: false, allowUnknownRevocation: false, allowNoClientCertificateList: true, allowNoRepositoryCertificateList: true); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var verificationProvider = new SignatureTrustAndValidityVerificationProvider(); using (var package = new PackageArchiveReader(nupkg.CreateAsStream(), leaveStreamOpen: false)) using (var testCertificate = new X509Certificate2(_trustedTestCert.Source.Cert)) using (var signatureRequest = new AuthorSignPackageRequest(testCertificate, HashAlgorithmName.SHA256)) { var signature = await SignedArchiveTestUtility.CreatePrimarySignatureForPackageAsync(package, signatureRequest); var timestampedSignature = await SignedArchiveTestUtility.TimestampSignature(timestampProvider, signature, signatureRequest.TimestampHashAlgorithm, SignaturePlacement.PrimarySignature, testLogger); var reTimestampedSignature = await SignedArchiveTestUtility.TimestampSignature(timestampProvider, timestampedSignature, signatureRequest.TimestampHashAlgorithm, SignaturePlacement.PrimarySignature, testLogger); timestampedSignature.Timestamps.Count.Should().Be(1); reTimestampedSignature.Timestamps.Count.Should().Be(2); // Act var result = await verificationProvider.GetTrustResultAsync(package, reTimestampedSignature, setting, CancellationToken.None); var totalErrorIssues = result.GetErrorIssues(); // Assert result.Trust.Should().Be(SignatureVerificationStatus.Illegal); totalErrorIssues.Count().Should().Be(1); totalErrorIssues.First().Code.Should().Be(NuGetLogCode.NU3000); } }
public void NewTsViaFedict() { var provider = new Rfc3161TimestampProvider(); byte[] tsBytes = provider.GetTimestampFromDocumentHash(hash, "http://www.w3.org/2001/04/xmlenc#sha256"); TimeStampToken tst = tsBytes.ToTimeStampToken(); Assert.True(tst.IsMatch(new MemoryStream(msg))); //Validate Timestamp ts; IList <CertificateList> crls = new List <CertificateList>(); IList <BasicOcspResponse> ocps = new List <BasicOcspResponse>(); ts = tst.Validate(crls, ocps); Assert.True(Math.Abs((DateTime.UtcNow - ts.Time).TotalSeconds) < 60); if (ts.CertificateChain.ChainElements.Count == 2) { Assert.Equal(new DateTime(2022, 2, 28, 10, 0, 0), ts.RenewalTime); Assert.Equal(0, ocps.Count); Assert.Equal(1, crls.Count); } else if (ts.CertificateChain.ChainElements.Count == 3) { Assert.Equal(new DateTime(2031, 01, 21, 0, 0, 0), ts.RenewalTime); Assert.Equal(2, ocps.Count); Assert.Equal(0, crls.Count); } else { Assert.True(false, "The chain should be 3 (win) or 2 (linux) long"); } Assert.Equal(0, ts.TimestampStatus.Count(x => x.Status != X509ChainStatusFlags.NoError)); Assert.Equal(0, ts.CertificateChain.ChainStatus.Count(x => x.Status != X509ChainStatusFlags.NoError)); ts = tst.Validate(crls, ocps, DateTime.UtcNow); //check clock skewness Assert.True(Math.Abs((DateTime.UtcNow - ts.Time).TotalSeconds) < 60); //Assert.AreEqual(new DateTime(2022, 2, 28, 10, 0, 0), ts.RenewalTime); Assert.Equal(0, ts.TimestampStatus.Count(x => x.Status != X509ChainStatusFlags.NoError)); Assert.Equal(0, ts.CertificateChain.ChainStatus.Count(x => x.Status != X509ChainStatusFlags.NoError)); }
public void NewTsViaFedict() { var provider = new Rfc3161TimestampProvider(); byte[] tsBytes = provider.GetTimestampFromDocumentHash(hash, "http://www.w3.org/2001/04/xmlenc#sha256"); TimeStampToken tst = tsBytes.ToTimeStampToken(); Assert.IsTrue(tst.IsMatch(new MemoryStream(msg))); //Validate Timestamp ts; IList <CertificateList> crls = new List <CertificateList>(); IList <BasicOcspResponse> ocps = new List <BasicOcspResponse>(); ts = tst.Validate(crls, ocps); Assert.IsTrue(Math.Abs((DateTime.UtcNow - ts.Time).TotalSeconds) < 60); Assert.AreEqual(new DateTime(2021, 12, 15, 8, 0, 0), ts.RenewalTime); Assert.AreEqual(0, ts.TimestampStatus.Count(x => x.Status != X509ChainStatusFlags.NoError)); Assert.AreEqual(0, ts.CertificateChain.ChainStatus.Count(x => x.Status != X509ChainStatusFlags.NoError)); }
public async Task GetTimestamp_WhenRequestNull_Throws() { var logger = new TestLogger(); var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var authorCertName = "*****@*****.**"; var content = new SignatureContent(SigningSpecifications.V1, Common.HashAlgorithmName.SHA256, "Test data to be signed and timestamped"); Action <X509V3CertificateGenerator> modifyGenerator = delegate(X509V3CertificateGenerator gen) { gen.SetNotBefore(DateTime.MinValue); gen.SetNotBefore(DateTime.UtcNow.Subtract(TimeSpan.FromDays(1))); // cert has expired }; using (var authorCert = SigningTestUtility.GenerateCertificate(authorCertName, modifyGenerator: modifyGenerator)) { var timestampHashAlgorithm = Common.HashAlgorithmName.SHA256; var signedCms = SigningTestUtility.GenerateSignedCms(authorCert, content.GetBytes()); var signature = PrimarySignature.Load(signedCms.Encode()); var signatureValue = signature.GetSignatureValue(); var messageHash = timestampHashAlgorithm.ComputeHash(signatureValue); var request = new TimestampRequest( signingSpecifications: SigningSpecifications.V1, hashedMessage: messageHash, hashAlgorithm: timestampHashAlgorithm, target: SignaturePlacement.PrimarySignature ); // Act Action timestampAction = () => timestampProvider.GetTimestamp(null, logger, CancellationToken.None); // Assert timestampAction.ShouldThrow <ArgumentNullException>() .WithMessage(string.Format(_argumentNullExceptionMessage, nameof(request))); } }
public async Task TimestampData_WhenTimestampSigningCertificateRevoked_Throws() { var testServer = await _testFixture.GetSigningTestServerAsync(); var certificateAuthority = await _testFixture.GetDefaultTrustedCertificateAuthorityAsync(); var timestampService = TimestampService.Create(certificateAuthority); certificateAuthority.Revoke(timestampService.Certificate, CrlReason.KeyCompromise, DateTimeOffset.UtcNow); using (testServer.RegisterResponder(timestampService)) { var logger = new TestLogger(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var data = "Test data to be signed and timestamped"; using (var authorCert = new X509Certificate2(_trustedTestCert.Source.Cert)) { var signedCms = SigningTestUtility.GenerateSignedCms(authorCert, Encoding.ASCII.GetBytes(data)); var signatureValue = signedCms.Encode(); var request = new TimestampRequest { SigningSpec = SigningSpecifications.V1, TimestampHashAlgorithm = Common.HashAlgorithmName.SHA256, SignatureValue = signatureValue }; var exception = Assert.Throws <TimestampException>( () => timestampProvider.TimestampData(request, logger, CancellationToken.None)); Assert.Equal( "The timestamp service's certificate chain could not be built: The certificate is revoked.", exception.Message); } } }
public async Task GetTimestampAsync_WhenRequestNull_ThrowsAsync() { var logger = new TestLogger(); var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var authorCertName = "*****@*****.**"; var content = new SignatureContent(SigningSpecifications.V1, Common.HashAlgorithmName.SHA256, "Test data to be signed and timestamped"); Action <TestCertificateGenerator> modifyGenerator = delegate(TestCertificateGenerator gen) { gen.NotBefore = DateTime.UtcNow.Subtract(TimeSpan.FromDays(1)); // cert has expired }; using (var authorCert = SigningTestUtility.GenerateCertificate(authorCertName, modifyGenerator: modifyGenerator)) { var timestampHashAlgorithm = Common.HashAlgorithmName.SHA256; var signedCms = SigningTestUtility.GenerateSignedCms(authorCert, content.GetBytes()); var signature = PrimarySignature.Load(signedCms.Encode()); var signatureValue = signature.GetSignatureValue(); var messageHash = timestampHashAlgorithm.ComputeHash(signatureValue); var request = new TimestampRequest( signingSpecifications: SigningSpecifications.V1, hashedMessage: messageHash, hashAlgorithm: timestampHashAlgorithm, target: SignaturePlacement.PrimarySignature ); // Assert var exception = await Assert.ThrowsAsync <ArgumentNullException>( () => timestampProvider.GetTimestampAsync(request: null, logger, CancellationToken.None)); Assert.Equal("request", exception.ParamName); Assert.StartsWith("Value cannot be null.", exception.Message); } }
public static async Task CreateSignedPackageAsync( SignPackageRequest request, Stream packageReadStream, Stream packageWriteStream, Uri timestampService = null) { Rfc3161TimestampProvider timestampProvider = null; if (timestampService != null) { timestampProvider = new Rfc3161TimestampProvider(timestampService); } using (var signedPackage = new SignedPackageArchive(packageReadStream, packageWriteStream)) using (var options = new SigningOptions( new Lazy <Stream>(() => packageReadStream), new Lazy <Stream>(() => packageWriteStream), overwrite: false, signatureProvider: new X509SignatureProvider(timestampProvider), logger: NullLogger.Instance)) { await SigningUtility.SignAsync(options, request, CancellationToken.None); } }
public void Rfc3161TimestampProvider_Success() { // Arrange var logger = new TestLogger(); var timestampProvider = new Rfc3161TimestampProvider(new Uri(_testTimestampServer)); var data = "Test data to be signed and timestamped"; using (var authorCert = new X509Certificate2(_trustedTestCert.Source.Cert)) { var signedCms = SigningTestUtility.GenerateSignedCms(authorCert, Encoding.ASCII.GetBytes(data)); var signatureValue = signedCms.Encode(); var request = new TimestampRequest { Certificate = authorCert, SigningSpec = SigningSpecifications.V1, TimestampHashAlgorithm = Common.HashAlgorithmName.SHA256, SignatureValue = signatureValue }; // Act var timestampedData = timestampProvider.TimestampData(request, logger, CancellationToken.None); var timestampedCms = new SignedCms(); timestampedCms.Decode(timestampedData); // Assert timestampedData.Should().NotBeNull(); timestampedCms.Should().NotBeNull(); timestampedCms.Detached.Should().BeFalse(); timestampedCms.ContentInfo.Should().NotBeNull(); timestampedCms.Certificates.Count.Should().Be(1); timestampedCms.SignerInfos.Count.Should().Be(1); timestampedCms.SignerInfos[0].UnsignedAttributes.Count.Should().Be(1); timestampedCms.SignerInfos[0].UnsignedAttributes[0].Oid.Value.Should().Be(Oids.SignatureTimeStampTokenAttributeOid); } }
public void EnsureValidNonce_Always_EnsuresValidNonce(byte[] actualNonce, byte[] expectedNonce) { Rfc3161TimestampProvider.EnsureValidNonce(actualNonce); Assert.Equal(expectedNonce, actualNonce); }
public async Task Timestamp_Verify_WithOfflineRevocation_ReturnsCorrectFlagsAndLogsAsync() { var nupkg = new SimpleTestPackageContext(); using (var testServer = await SigningTestServer.CreateAsync()) using (var responders = new DisposableList <IDisposable>()) using (var packageStream = await nupkg.CreateAsStreamAsync()) using (var testCertificate = new X509Certificate2(_trustedTestCert.Source.Cert)) { CertificateAuthority rootCa = CertificateAuthority.Create(testServer.Url); CertificateAuthority intermediateCa = rootCa.CreateIntermediateCertificateAuthority(); responders.Add(testServer.RegisterResponder(intermediateCa)); responders.Add(testServer.RegisterResponder(rootCa)); StoreLocation storeLocation = CertificateStoreUtilities.GetTrustedCertificateStoreLocation(); using (var trustedServerRoot = TrustedTestCert.Create( new X509Certificate2(rootCa.Certificate.GetEncoded()), StoreName.Root, storeLocation)) { var timestampService = TimestampService.Create(intermediateCa); responders.Add(testServer.RegisterResponder(timestampService)); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); AuthorPrimarySignature signature = await SignedArchiveTestUtility.CreateAuthorSignatureForPackageAsync(testCertificate, packageStream, timestampProvider); var timestamp = signature.Timestamps.First(); var settings = new SignedPackageVerifierSettings( allowUnsigned: false, allowUntrusted: false, allowIllegal: false, allowIgnoreTimestamp: false, allowMultipleTimestamps: false, allowNoTimestamp: false, allowUnknownRevocation: false, reportUnknownRevocation: true, verificationTarget: VerificationTarget.All, signaturePlacement: SignaturePlacement.Any, repositoryCountersignatureVerificationBehavior: SignatureVerificationBehavior.Always, revocationMode: RevocationMode.Online); var logs = new List <SignatureLog>(); var result = timestamp.Verify(signature, settings, HashAlgorithmName.SHA256, logs); result.HasFlag(SignatureVerificationStatusFlags.UnknownRevocation).Should().BeTrue(); var errors = logs.Where(l => l.Level == LogLevel.Error); if (RuntimeEnvironmentHelper.IsMacOSX) { errors.Count().Should().Be(1); } else { errors.Count().Should().Be(2); SigningTestUtility.AssertOfflineRevocationOnlineMode(errors, LogLevel.Error, NuGetLogCode.NU3028); } SigningTestUtility.AssertRevocationStatusUnknown(errors, LogLevel.Error, NuGetLogCode.NU3028); } } }