public async Task VerifySignaturesAsync_ValidCertificateAndTimestamp_Success()
        {
            // Arrange
            var nupkg            = new SimpleTestPackageContext();
            var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync();

            using (var dir = TestDirectory.Create())
                using (var testCertificate = new X509Certificate2(_trustedTestCert.Source.Cert))
                {
                    var signedPackagePath = await SignedArchiveTestUtility.CreateSignedAndTimeStampedPackageAsync(
                        testCertificate,
                        nupkg,
                        dir,
                        timestampService.Url);

                    var verifier = new PackageSignatureVerifier(_trustProviders, SignedPackageVerifierSettings.VerifyCommandDefaultPolicy);
                    using (var packageReader = new PackageArchiveReader(signedPackagePath))
                    {
                        // Act
                        var result = await verifier.VerifySignaturesAsync(packageReader, CancellationToken.None);

                        var resultsWithErrors = result.Results.Where(r => r.GetErrorIssues().Any());

                        // Assert
                        result.Valid.Should().BeTrue();
                        resultsWithErrors.Count().Should().Be(0);
                    }
                }
        }
Esempio n. 2
0
        public async Task VerifySignaturesAsync_ValidCertificateAndTimestampWithDifferentHashAlgorithms_Success()
        {
            var packageContext   = new SimpleTestPackageContext();
            var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync();

            using (var directory = TestDirectory.Create())
                using (var certificate = new X509Certificate2(_trustedTestCert.Source.Cert))
                {
                    var request           = new AuthorSignPackageRequest(certificate, HashAlgorithmName.SHA512, HashAlgorithmName.SHA256);
                    var signedPackagePath = await SignedArchiveTestUtility.CreateSignedAndTimeStampedPackageAsync(
                        certificate,
                        packageContext,
                        directory,
                        timestampService.Url,
                        request);

                    var verifier = new PackageSignatureVerifier(_trustProviders, SignedPackageVerifierSettings.VerifyCommandDefaultPolicy);
                    using (var packageReader = new PackageArchiveReader(signedPackagePath))
                    {
                        var result = await verifier.VerifySignaturesAsync(packageReader, CancellationToken.None);

                        var resultsWithErrors = result.Results.Where(r => r.GetErrorIssues().Any());

                        result.Valid.Should().BeTrue();
                        resultsWithErrors.Count().Should().Be(0);
                    }
                }
        }
        public async Task GetTrustResultAsync_WithInvalidSignature_Throws()
        {
            var package          = new SimpleTestPackageContext();
            var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync();

            using (var directory = TestDirectory.Create())
                using (var testCertificate = new X509Certificate2(_trustedTestCert.Source.Cert))
                {
                    var packageFilePath = await SignedArchiveTestUtility.CreateSignedAndTimeStampedPackageAsync(
                        testCertificate,
                        package,
                        directory,
                        timestampService.Url);

                    using (var packageReader = new PackageArchiveReader(packageFilePath))
                    {
                        var signature = await packageReader.GetSignatureAsync(CancellationToken.None);

                        var invalidSignature = SignedArchiveTestUtility.GenerateInvalidSignature(signature);
                        var provider         = new SignatureTrustAndValidityVerificationProvider();

                        var result = await provider.GetTrustResultAsync(
                            packageReader,
                            invalidSignature,
                            SignedPackageVerifierSettings.Default,
                            CancellationToken.None);

                        var issue = result.Issues.FirstOrDefault(log => log.Code == NuGetLogCode.NU3012);

                        Assert.NotNull(issue);
                        Assert.Equal("Primary signature validation failed.", issue.Message);
                    }
                }
        }
Esempio n. 4
0
        public async Task Signature_HasTimestamp()
        {
            // Arrange
            var nupkg            = new SimpleTestPackageContext();
            var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync();

            using (var dir = TestDirectory.Create())
            {
                // Act
                var signedPackagePath = await SignedArchiveTestUtility.CreateSignedAndTimeStampedPackageAsync(
                    _trustedTestCert.Source.Cert,
                    nupkg,
                    dir,
                    timestampService.Url);

                // Assert
                using (var stream = File.OpenRead(signedPackagePath))
                    using (var reader = new PackageArchiveReader(stream))
                    {
                        var signature = await reader.GetSignatureAsync(CancellationToken.None);

                        signature.Should().NotBeNull();
                        signature.Timestamps.Should().NotBeEmpty();
                    }
            }
        }
Esempio n. 5
0
        public async Task GetTrustResultAsync_WithNoSigningCertificate_Throws()
        {
            var package = new SimpleTestPackageContext();

            using (var directory = TestDirectory.Create())
                using (var testCertificate = new X509Certificate2(_trustedTestCert.Source.Cert))
                {
                    var packageFilePath = await SignedArchiveTestUtility.CreateSignedAndTimeStampedPackageAsync(testCertificate, package, directory);

                    using (var packageReader = new PackageArchiveReader(packageFilePath))
                    {
                        var signature = (await packageReader.GetSignaturesAsync(CancellationToken.None)).Single();
                        var signatureWithNoCertificates = GenerateSignatureWithNoCertificates(signature);
                        var provider = new SignatureTrustAndValidityVerificationProvider();

                        var result = await provider.GetTrustResultAsync(
                            packageReader,
                            signatureWithNoCertificates,
                            SignedPackageVerifierSettings.Default,
                            CancellationToken.None);

                        var issue = result.Issues.FirstOrDefault(log => log.Code == NuGetLogCode.NU3010);

                        Assert.NotNull(issue);
                        Assert.Equal("The primary signature does not have a signing certificate.", issue.Message);
                    }
                }
        }
Esempio n. 6
0
        public async Task VerifySignaturesAsync_ExpiredCertificateAndTimestamp_Success()
        {
            var ca = await _testFixture.GetDefaultTrustedCertificateAuthorityAsync();

            var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync();

            var keyPair      = SigningTestUtility.GenerateKeyPair(publicKeyLength: 2048);
            var now          = DateTimeOffset.UtcNow;
            var issueOptions = new IssueCertificateOptions()
            {
                KeyPair     = keyPair,
                NotAfter    = now.AddSeconds(10),
                NotBefore   = now.AddSeconds(-2),
                SubjectName = new X509Name("CN=NuGet Test Expired Certificate")
            };
            var bcCertificate = ca.IssueCertificate(issueOptions);

            using (var certificate = new X509Certificate2(bcCertificate.GetEncoded()))
                using (var directory = TestDirectory.Create())
                {
                    certificate.PrivateKey = DotNetUtilities.ToRSA(keyPair.Private as RsaPrivateCrtKeyParameters);

                    var packageContext    = new SimpleTestPackageContext();
                    var signedPackagePath = await SignedArchiveTestUtility.CreateSignedAndTimeStampedPackageAsync(
                        certificate,
                        packageContext,
                        directory,
                        timestampService.Url);

                    var notAfter     = certificate.NotAfter.ToUniversalTime();
                    var waitDuration = (notAfter - DateTimeOffset.UtcNow).Add(TimeSpan.FromSeconds(1));

                    // Wait for the certificate to expire.  Trust of the signature will require a valid timestamp.
                    await Task.Delay(waitDuration);

                    Assert.True(DateTime.UtcNow > notAfter);

                    var verifier = new PackageSignatureVerifier(_trustProviders, SignedPackageVerifierSettings.VerifyCommandDefaultPolicy);

                    using (var packageReader = new PackageArchiveReader(signedPackagePath))
                    {
                        var result = await verifier.VerifySignaturesAsync(packageReader, CancellationToken.None);

                        var trustProvider = result.Results.Single();

                        Assert.True(result.Valid);
                        Assert.Equal(SignatureVerificationStatus.Trusted, trustProvider.Trust);
                        Assert.Equal(0, trustProvider.Issues.Count(issue => issue.Level == LogLevel.Error));
                        Assert.Equal(0, trustProvider.Issues.Count(issue => issue.Level == LogLevel.Warning));
                    }
                }
        }
Esempio n. 7
0
        public async Task Signature_HasTimestamp()
        {
            // Arrange
            var nupkg      = new SimpleTestPackageContext();
            var testLogger = new TestLogger();

            using (var dir = TestDirectory.Create())
            {
                // Act
                var signedPackagePath = await SignedArchiveTestUtility.CreateSignedAndTimeStampedPackageAsync(_trustedTestCert.Source.Cert, nupkg, dir);

                // Assert
                using (var stream = File.OpenRead(signedPackagePath))
                    using (var reader = new PackageArchiveReader(stream))
                    {
                        var signatures = await reader.GetSignaturesAsync(CancellationToken.None);

                        signatures.Count.Should().Be(1);

                        var signature = signatures[0];
                        signature.Timestamps.Should().NotBeEmpty();
                    }
            }
        }
Esempio n. 8
0
        public async Task VerifySignaturesAsync_ExpiredCertificateAndTimestampWithTooLargeRange_Fails()
        {
            var testServer = await _testFixture.GetSigningTestServerAsync();

            var ca = await _testFixture.GetDefaultTrustedCertificateAuthorityAsync();

            var accuracy       = new BcAccuracy(seconds: new DerInteger(30), millis: null, micros: null);
            var serviceOptions = new TimestampServiceOptions()
            {
                Accuracy = accuracy
            };
            var timestampService = TimestampService.Create(ca, serviceOptions);
            var keyPair          = SigningTestUtility.GenerateKeyPair(publicKeyLength: 2048);
            var now          = DateTimeOffset.UtcNow;
            var issueOptions = new IssueCertificateOptions()
            {
                KeyPair     = keyPair,
                NotAfter    = now.AddSeconds(10),
                NotBefore   = now.AddSeconds(-2),
                SubjectName = new X509Name("CN=NuGet Test Expired Certificate")
            };
            var bcCertificate = ca.IssueCertificate(issueOptions);

            using (testServer.RegisterResponder(timestampService))
                using (var certificate = new X509Certificate2(bcCertificate.GetEncoded()))
                    using (var directory = TestDirectory.Create())
                    {
                        certificate.PrivateKey = DotNetUtilities.ToRSA(keyPair.Private as RsaPrivateCrtKeyParameters);

                        var packageContext    = new SimpleTestPackageContext();
                        var signedPackagePath = await SignedArchiveTestUtility.CreateSignedAndTimeStampedPackageAsync(
                            certificate,
                            packageContext,
                            directory,
                            timestampService.Url);

                        var waitDuration = (issueOptions.NotAfter - DateTimeOffset.UtcNow).Add(TimeSpan.FromSeconds(1));

                        // Wait for the certificate to expire.  Trust of the signature will require a valid timestamp.
                        if (waitDuration > TimeSpan.Zero)
                        {
                            await Task.Delay(waitDuration);
                        }

                        Assert.True(DateTime.UtcNow > issueOptions.NotAfter);

                        var verifier = new PackageSignatureVerifier(_trustProviders, SignedPackageVerifierSettings.VerifyCommandDefaultPolicy);

                        using (var packageReader = new PackageArchiveReader(signedPackagePath))
                        {
                            var results = await verifier.VerifySignaturesAsync(packageReader, CancellationToken.None);

                            var result = results.Results.Single();

                            Assert.False(results.Valid);
                            Assert.Equal(SignatureVerificationStatus.Untrusted, result.Trust);
                            Assert.Equal(1, result.Issues.Count(issue => issue.Level == LogLevel.Error));
                            Assert.Equal(0, result.Issues.Count(issue => issue.Level == LogLevel.Warning));

                            Assert.Contains(result.Issues, issue =>
                                            issue.Code == NuGetLogCode.NU3011 &&
                                            issue.Level == LogLevel.Error &&
                                            issue.Message == "The primary signature validity period has expired.");
                        }
                    }
        }