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);
                }
        }
Exemplo n.º 2
0
        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();
                        }
                    }
                }
        }
Exemplo n.º 3
0
        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"));
                            }
                        }
        }
Exemplo n.º 4
0
        public async Task HasRepositoryCountersignature_WithSignatureWithoutRepositoryCountersignature_ReturnsFalseAsync()
        {
            using (var certificate = _fixture.GetDefaultCertificate())
            {
                var packageContext        = new SimpleTestPackageContext();
                var unsignedPackageStream = packageContext.CreateAsStream();

                var signature = await SignedArchiveTestUtility.CreateAuthorSignatureForPackageAsync(
                    certificate,
                    unsignedPackageStream);

                var hasRepoCountersignature = SignatureUtility.HasRepositoryCountersignature(signature);

                Assert.False(hasRepoCountersignature);
            }
        }
Exemplo n.º 5
0
        public async Task HasRepositoryCountersignature_WithSignatureWithRepositoryCountersignature_ReturnsTrueAsync()
        {
            using (var certificate = _fixture.GetDefaultCertificate())
                using (var repositoryCertificate = _fixture.GetDefaultCertificate())
                {
                    var packageContext        = new SimpleTestPackageContext();
                    var unsignedPackageStream = packageContext.CreateAsStream();

                    var signature = await SignedArchiveTestUtility.CreateAuthorSignatureForPackageAsync(
                        certificate,
                        unsignedPackageStream);

                    var hashAlgorithm     = Common.HashAlgorithmName.SHA256;
                    var v3ServiceIndexUri = new Uri("https://v3serviceIndex.test/api/index.json");
                    using (var request = new RepositorySignPackageRequest(repositoryCertificate, hashAlgorithm, hashAlgorithm, v3ServiceIndexUri, null))
                    {
                        var reposignedSignature = await SignedArchiveTestUtility.RepositoryCountersignPrimarySignatureAsync(signature, request);

                        var hasRepoCountersignature = SignatureUtility.HasRepositoryCountersignature(reposignedSignature);

                        Assert.True(hasRepoCountersignature);
                    }
                }
        }
Exemplo n.º 6
0
        public async Task Restore_PackageWithCompressedSignature_RequireMode_FailsAndDoesNotExpandAsync()
        {
            // Arrange
            var packageX = new SimpleTestPackageContext();

            using (var pathContext = new SimpleTestPathContext())
                using (var packageStream = await packageX.CreateAsStreamAsync())
                    using (var testCertificate = new X509Certificate2(_trustedTestCert.Source.Cert))
                    {
                        var signature = await SignedArchiveTestUtility.CreateAuthorSignatureForPackageAsync(testCertificate, packageStream);

                        using (var package = new ZipArchive(packageStream, ZipArchiveMode.Update, leaveOpen: true))
                        {
                            var signatureEntry = package.CreateEntry(SigningSpecifications.V1.SignaturePath);
                            using (var signatureStream = new MemoryStream(signature.GetBytes()))
                                using (var signatureEntryStream = signatureEntry.Open())
                                {
                                    signatureStream.CopyTo(signatureEntryStream);
                                }
                        }

                        var packagePath = Path.Combine(pathContext.PackageSource, $"{packageX.ToString()}.nupkg");
                        packageStream.Seek(offset: 0, loc: SeekOrigin.Begin);

                        using (var fileStream = File.OpenWrite(packagePath))
                        {
                            packageStream.CopyTo(fileStream);
                        }

                        // Set up solution, project, and packages
                        var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                        var propsFile = Path.Combine(pathContext.SolutionRoot, "NuGet.Config");

                        using (var stream = File.OpenWrite(propsFile))
                            using (var textWritter = new StreamWriter(stream))
                            {
                                textWritter.Write(@"<configuration><config><add key=""signatureValidationMode"" value=""require"" /></config></configuration>");
                            }

                        var projectA = SimpleTestProjectContext.CreateNETCore(
                            "a",
                            pathContext.SolutionRoot,
                            NuGetFramework.Parse("NETStandard2.0"));

                        projectA.AddPackageToAllFrameworks(packageX);
                        solution.Projects.Add(projectA);
                        solution.Create(pathContext.SolutionRoot);

                        var args = new string[]
                        {
                            projectA.ProjectPath
                        };

                        // Act
                        var result          = RunRestore(_nugetExePath, pathContext, expectedExitCode: 1, additionalArgs: args);
                        var assetFileReader = new LockFileFormat();
                        var assetsFile      = assetFileReader.Read(projectA.AssetsFileOutputPath);
                        var errors          = assetsFile.LogMessages.Where(m => m.Level == LogLevel.Error);
                        var warnings        = assetsFile.LogMessages.Where(m => m.Level == LogLevel.Warning);

                        // Assert
                        result.ExitCode.Should().Be(1);
                        result.Errors.Should().Contain(string.Format(_NU3005, SigningTestUtility.AddSignatureLogPrefix(_NU3005CompressedMessage, packageX.Identity, pathContext.PackageSource)));

                        errors.Count().Should().Be(1);
                        errors.First().Code.Should().Be(NuGetLogCode.NU3005);
                        errors.First().Message.Should().Be(SigningTestUtility.AddSignatureLogPrefix(_NU3005CompressedMessage, packageX.Identity, pathContext.PackageSource));
                        errors.First().LibraryId.Should().Be(packageX.Identity.Id.ToString());

                        warnings.Count().Should().Be(0);

                        var installedPackageDir = Path.Combine(pathContext.UserPackagesFolder, packageX.Identity.Id);
                        Directory.Exists(installedPackageDir).Should().BeFalse();
                    }
        }
Exemplo n.º 7
0
        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);
                            }
                        }
        }