public async Task GetTrustResultAsync_WithUnavailableRevocationInformationInAcceptMode_DoesNotWarnAsync()
        {
            // Arrange
            var setting = SignedPackageVerifierSettings.GetAcceptModeDefaultPolicy();

            // Act & Assert
            var matchingIssues = await VerifyUnavailableRevocationInfoAsync(
                SignatureVerificationStatus.Valid,
                LogLevel.Warning,
                setting);

            Assert.Empty(matchingIssues);
        }
Exemplo n.º 2
0
        public Task <PackageVerificationResult> GetTrustResultAsync(
            ISignedPackageReader package,
            PrimarySignature signature,
            SignedPackageVerifierSettings settings,
            CancellationToken token)
        {
            var result = new SignedPackageVerificationResult(
                SignatureVerificationStatus.Valid,
                signature,
                Enumerable.Empty <SignatureLog>());

            return(Task.FromResult <PackageVerificationResult>(result));
        }
Exemplo n.º 3
0
        public async Task GetTrustResultAsync_VerifyWithoutCertificateInAllowListWithAllowUntrusted_Warn()
        {
            // Arrange
            var nupkg = new SimpleTestPackageContext();

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

                    var allowListHashes = new[] { "abc" };
                    var allowList       = allowListHashes.Select(hash => new CertificateHashAllowListEntry(VerificationTarget.Primary, hash)).ToList();

                    var trustProviders = new[]
                    {
                        new AllowListVerificationProvider(allowList)
                    };

                    var settings = new SignedPackageVerifierSettings(
                        allowUnsigned: false,
                        allowIllegal: false,
                        allowUntrusted: true,
                        allowUntrustedSelfIssuedCertificate: true,
                        allowIgnoreTimestamp: true,
                        allowMultipleTimestamps: true,
                        allowNoTimestamp: true,
                        allowUnknownRevocation: true);

                    var verifier = new PackageSignatureVerifier(trustProviders, settings);

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

                        var resultsWithErrors   = result.Results.Where(r => r.GetErrorIssues().Any());
                        var resultsWithWarnings = result.Results.Where(r => r.GetWarningIssues().Any());
                        var totalErrorIssues    = resultsWithErrors.SelectMany(r => r.GetErrorIssues());
                        var totalWarningIssues  = resultsWithWarnings.SelectMany(r => r.GetWarningIssues());

                        // Assert
                        result.Valid.Should().BeTrue();
                        resultsWithErrors.Count().Should().Be(0);
                        resultsWithWarnings.Count().Should().Be(1);
                        totalErrorIssues.Count().Should().Be(0);
                        totalWarningIssues.Count().Should().Be(1);
                        totalWarningIssues.First().Code.Should().Be(NuGetLogCode.NU3003);
                        totalWarningIssues.First().Message.Should().Contain(_noCertInAllowList);
                    }
                }
        }
Exemplo n.º 4
0
        public async Task VerifySignaturesAsync_WithExpiredPrimarySignature_ValidCountersignature_AndPrimarySignatureExpiredAtCountersignTime_Fails()
        {
            // Arrange
            var nupkg            = new SimpleTestPackageContext();
            var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync();

            var settings = new SignedPackageVerifierSettings(
                allowUnsigned: false,
                allowIllegal: false,
                allowUntrusted: false,
                allowIgnoreTimestamp: true,
                allowMultipleTimestamps: true,
                allowNoTimestamp: true,
                allowUnknownRevocation: true,
                alwaysVerifyCountersignature: true,
                allowNoClientCertificateList: true,
                allowNoRepositoryCertificateList: true);

            using (var dir = TestDirectory.Create())
                using (var willExpireCert = new X509Certificate2(_testFixture.TrustedTestCertificateWillExpireIn5Seconds.Source.Cert))
                    using (var repoTestCertificate = new X509Certificate2(_trustedTestCert.Source.Cert))
                    {
                        DateTimeOffset certExpiration = DateTime.SpecifyKind(willExpireCert.NotAfter, DateTimeKind.Local);

                        var signedPackagePath = await SignedArchiveTestUtility.AuthorSignPackageAsync(
                            willExpireCert,
                            nupkg,
                            dir);

                        // Wait for cert to expire
                        while (certExpiration > DateTimeOffset.Now)
                        {
                            Thread.Sleep(100);
                        }

                        var countersignedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(repoTestCertificate, signedPackagePath, dir, new Uri("https://v3serviceIndex.test/api/index.json"), timestampService.Url);

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

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

                            // Assert
                            result.Valid.Should().BeFalse();
                            resultsWithErrors.Count().Should().Be(1);
                        }
                    }
        }
        private static SignedPackageVerifierSettings GetSettingsPolicy(string policyString)
        {
            if (StringComparer.Ordinal.Equals(policyString, "command"))
            {
                return(SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy());
            }

            if (StringComparer.Ordinal.Equals(policyString, "vs"))
            {
                return(SignedPackageVerifierSettings.GetAcceptModeDefaultPolicy());
            }

            return(SignedPackageVerifierSettings.GetDefault());
        }
Exemplo n.º 6
0
        private static SignedPackageVerifierSettings GetSettingsPolicy(string policyString)
        {
            if (StringComparer.Ordinal.Equals(policyString, "command"))
            {
                return(SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy(TestEnvironmentVariableReader.EmptyInstance));
            }

            if (StringComparer.Ordinal.Equals(policyString, "vs"))
            {
                return(SignedPackageVerifierSettings.GetAcceptModeDefaultPolicy(TestEnvironmentVariableReader.EmptyInstance));
            }

            return(SignedPackageVerifierSettings.GetDefault(TestEnvironmentVariableReader.EmptyInstance));
        }
Exemplo n.º 7
0
 public static bool AreVerifierSettingsEqual(SignedPackageVerifierSettings first, SignedPackageVerifierSettings second)
 {
     return(first.AllowIgnoreTimestamp == second.AllowIgnoreTimestamp &&
            first.AllowIllegal == second.AllowIllegal &&
            first.AllowMultipleTimestamps == second.AllowMultipleTimestamps &&
            first.AllowNoTimestamp == second.AllowNoTimestamp &&
            first.AllowUnknownRevocation == second.AllowUnknownRevocation &&
            first.ReportUnknownRevocation == second.ReportUnknownRevocation &&
            first.AllowUnsigned == second.AllowUnsigned &&
            first.AllowUntrusted == second.AllowUntrusted &&
            first.VerificationTarget == second.VerificationTarget &&
            first.SignaturePlacement == second.SignaturePlacement &&
            first.RepositoryCountersignatureVerificationBehavior == second.RepositoryCountersignatureVerificationBehavior);
 }
Exemplo n.º 8
0
 public AllowListVerificationProviderTests(SigningTestFixture fixture)
 {
     _testFixture     = fixture ?? throw new ArgumentNullException(nameof(fixture));
     _trustedTestCert = _testFixture.TrustedTestCertificate;
     _settings        = new SignedPackageVerifierSettings(
         allowUnsigned: false,
         allowIllegal: false,
         allowUntrusted: false,
         allowUntrustedSelfIssuedCertificate: true,
         allowIgnoreTimestamp: true,
         allowMultipleTimestamps: true,
         allowNoTimestamp: true,
         allowUnknownRevocation: true);
 }
            public async Task VerifySignaturesAsync_WithExpiredAndUntrustedPrimarySignature_ValidCountersignature_AndPrimarySignatureValidAtCountersignTime_SucceedsAsync()
            {
                var nupkg = new SimpleTestPackageContext();
                TimestampService timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync();

                var settings = new SignedPackageVerifierSettings(
                    allowUnsigned: false,
                    allowIllegal: false,
                    allowUntrusted: false,
                    allowIgnoreTimestamp: true,
                    allowMultipleTimestamps: true,
                    allowNoTimestamp: true,
                    allowUnknownRevocation: true,
                    reportUnknownRevocation: true,
                    verificationTarget: VerificationTarget.All,
                    signaturePlacement: SignaturePlacement.Any,
                    repositoryCountersignatureVerificationBehavior: SignatureVerificationBehavior.IfExistsAndIsNecessary,
                    revocationMode: RevocationMode.Online);
                var verifier = new PackageSignatureVerifier(_trustProviders);

                using (TestDirectory testDirectory = TestDirectory.Create())
                    using (X509Certificate2 untrustedCertificate = _testFixture.CreateUntrustedTestCertificateThatWillExpireSoon().Cert)
                        using (var repositoryCertificate = new X509Certificate2(_testFixture.TrustedRepositoryCertificate.Source.Cert))
                        {
                            string signedPackagePath = await SignedArchiveTestUtility.AuthorSignPackageAsync(
                                untrustedCertificate,
                                nupkg,
                                testDirectory);

                            string countersignedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(
                                repositoryCertificate,
                                signedPackagePath,
                                testDirectory,
                                TestServiceIndexUrl,
                                timestampService.Url);

                            await SignatureTestUtility.WaitForCertificateExpirationAsync(untrustedCertificate);

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

                                IEnumerable <PackageVerificationResult> resultsWithErrors = result.Results.Where(r => r.GetErrorIssues().Any());

                                result.IsValid.Should().BeTrue();
                                resultsWithErrors.Count().Should().Be(0);
                            }
                        }
            }
Exemplo n.º 10
0
        public async Task <int> ExecuteCommandAsync(VerifyArgs verifyArgs)
        {
            if (verifyArgs.Verifications.Count == 0)
            {
                verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_VerificationTypeNotSupported));
                return(FailureCode);
            }

            var errorCount = 0;

            if (ShouldExecuteVerification(verifyArgs, Verification.Signatures))
            {
                var packagesToVerify = LocalFolderUtility.ResolvePackageFromPath(verifyArgs.PackagePath);
                LocalFolderUtility.EnsurePackageFileExists(verifyArgs.PackagePath, packagesToVerify);

                var allowListEntries = verifyArgs.CertificateFingerprint.Select(fingerprint =>
                                                                                new CertificateHashAllowListEntry(
                                                                                    VerificationTarget.Author | VerificationTarget.Repository,
                                                                                    SignaturePlacement.PrimarySignature,
                                                                                    fingerprint,
                                                                                    _defaultFingerprintAlgorithm)).ToList();

                var verifierSettings      = SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy();
                var verificationProviders = SignatureVerificationProviderFactory.GetDefaultSignatureVerificationProviders();

                verificationProviders.Add(
                    new AllowListVerificationProvider(
                        allowListEntries,
                        requireNonEmptyAllowList: false,
                        noMatchErrorMessage: Strings.Error_NoMatchingCertificate));

                var verifier = new PackageSignatureVerifier(verificationProviders);

                foreach (var package in packagesToVerify)
                {
                    try
                    {
                        errorCount += await VerifySignatureForPackageAsync(package, verifyArgs.Logger, verifier, verifierSettings);
                    }
                    catch (InvalidDataException e)
                    {
                        verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_PackageIsNotValid, package));
                        ExceptionUtilities.LogException(e, verifyArgs.Logger);
                    }
                }
            }

            return(errorCount == 0 ? SuccessCode : FailureCode);
        }
            public async Task VerifySignaturesAsync_WithBasicSignedCms_SucceedsAsync()
            {
                var settings = new SignedPackageVerifierSettings(
                    allowUnsigned: false,
                    allowIllegal: false,
                    allowUntrusted: false,
                    allowIgnoreTimestamp: false,
                    allowMultipleTimestamps: true,
                    allowNoTimestamp: true,
                    allowUnknownRevocation: false,
                    reportUnknownRevocation: true,
                    verificationTarget: VerificationTarget.All,
                    signaturePlacement: SignaturePlacement.Any,
                    repositoryCountersignatureVerificationBehavior: SignatureVerificationBehavior.IfExistsAndIsNecessary,
                    revocationMode: RevocationMode.Online);

                using (TestDirectory directory = TestDirectory.Create())
                    using (var certificate = new X509Certificate2(_trustedTestCert.Source.Cert))
                    {
                        var      packageContext      = new SimpleTestPackageContext();
                        FileInfo unsignedPackageFile = await packageContext.CreateAsFileAsync(directory, "Package.nupkg");

                        FileInfo signedPackageFile = await SignedArchiveTestUtility.SignPackageFileWithBasicSignedCmsAsync(
                            directory,
                            unsignedPackageFile,
                            certificate);

                        var verifier = new PackageSignatureVerifier(_trustProviders);

                        using (var packageReader = new PackageArchiveReader(signedPackageFile.FullName))
                        {
                            VerifySignaturesResult result = await verifier.VerifySignaturesAsync(packageReader, settings, CancellationToken.None);

                            IEnumerable <PackageVerificationResult> resultsWithErrors = result.Results.Where(r => r.GetErrorIssues().Any());
                            IEnumerable <ILogMessage> totalErrorIssues = resultsWithErrors.SelectMany(r => r.GetErrorIssues());

                            Assert.Equal(1, result.Results.Count);

                            var        signedPackageVerificationResult = (SignedPackageVerificationResult)result.Results[0];
                            SignerInfo signer = signedPackageVerificationResult.Signature.SignedCms.SignerInfos[0];

                            Assert.Equal(0, signer.SignedAttributes.Count);
                            Assert.Equal(0, signer.UnsignedAttributes.Count);

                            Assert.Equal(0, resultsWithErrors.Count());
                            Assert.Equal(0, totalErrorIssues.Count());
                        }
                    }
            }
        public VSAPIProjectContext(bool skipAssemblyReferences, bool bindingRedirectsDisabled)
        {
            var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

            PackageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv2,
                PackageExtractionBehavior.XmlDocFileSaveMode,
                new LoggerAdapter(this),
                signedPackageVerifier,
                SignedPackageVerifierSettings.GetDefault());

            SourceControlManagerProvider = ServiceLocator.GetInstanceSafe <ISourceControlManagerProvider>();
            SkipAssemblyReferences       = skipAssemblyReferences;
            BindingRedirectsDisabled     = bindingRedirectsDisabled;
        }
Exemplo n.º 13
0
 public static bool AreVerifierSettingsEqual(SignedPackageVerifierSettings first, SignedPackageVerifierSettings second)
 {
     return(first.AllowIgnoreTimestamp == second.AllowIgnoreTimestamp &&
            first.AllowIllegal == second.AllowIllegal &&
            first.AllowMultipleTimestamps == second.AllowMultipleTimestamps &&
            first.AllowNoTimestamp == second.AllowNoTimestamp &&
            first.AllowUnknownRevocation == second.AllowUnknownRevocation &&
            first.AllowUnsigned == second.AllowUnsigned &&
            first.AllowUntrusted == second.AllowUntrusted &&
            first.AllowNoRepositoryCertificateList == second.AllowNoRepositoryCertificateList &&
            first.AllowNoClientCertificateList == second.AllowNoClientCertificateList &&
            first.AlwaysVerifyCountersignature == second.AlwaysVerifyCountersignature &&
            AreCertificateHashAllowListEqual(first.ClientCertificateList, second.ClientCertificateList) &&
            AreCertificateHashAllowListEqual(first.RepositoryCertificateList, second.RepositoryCertificateList));
 }
Exemplo n.º 14
0
        public async Task ClientPolicies_WithNoTrustedSignersListAsync(SigningTestType signature, string validationMode, bool expectedResult, int expectedErrors)
        {
            // Arrange
            using (var dir = TestDirectory.Create())
                using (var authorCertificate = new X509Certificate2(_trustedAuthorTestCert.Source.Cert))
                    using (var repoCertificate = new X509Certificate2(_trustedRepoTestCert.Source.Cert))
                    {
                        var authorCertificateFingerprintString = SignatureTestUtility.GetFingerprint(authorCertificate, HashAlgorithmName.SHA256);
                        var repoCertificateFingerprintString   = SignatureTestUtility.GetFingerprint(repoCertificate, HashAlgorithmName.SHA256);
                        var signedPackagePath = await CreateSignedPackageAsync(dir, signature, authorCertificate, repoCertificate);

                        var config = $@"
<configuration>
    <config>
        <add key=""signatureValidationMode"" value=""{validationMode}"" />
    </config>
</configuration>";

                        var nugetConfigPath = "NuGet.Config";
                        SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, dir, config);

                        // Act and Assert
                        var settings = new Settings(dir);

                        var verifierSettings = SignedPackageVerifierSettings.GetClientPolicy(settings, NullLogger.Instance);
                        var trustProviders   = new[]
                        {
                            new AllowListVerificationProvider()
                        };
                        var verifier = new PackageSignatureVerifier(trustProviders);

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

                            var resultsWithWarnings = result.Results.Where(r => r.GetWarningIssues().Any());
                            var resultsWithErrors   = result.Results.Where(r => r.GetErrorIssues().Any());
                            var totalWarningIssues  = resultsWithWarnings.SelectMany(r => r.GetWarningIssues());
                            var totalErrorIssues    = resultsWithErrors.SelectMany(r => r.GetErrorIssues());

                            // Assert
                            result.Valid.Should().Be(expectedResult);
                            totalWarningIssues.Count().Should().Be(0);
                            totalErrorIssues.Count().Should().Be(expectedErrors);
                        }
                    }
        }
Exemplo n.º 15
0
        private bool IsSigned(string path)
        {
            IEnumerable <ISignatureVerificationProvider> providers = SignatureVerificationProviderFactory.GetSignatureVerificationProviders();
            var packageSignatureVerifier = new PackageSignatureVerifier(providers);

            var verifierSettings = SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy(clientAllowListEntries: AllowListEntries);
            IEnumerable <ISignatureVerificationProvider> verificationProviders = SignatureVerificationProviderFactory.GetSignatureVerificationProviders();
            var verifier = new PackageSignatureVerifier(verificationProviders);

            using (var pr = new PackageArchiveReader(path))
            {
                Task <VerifySignaturesResult> verifySignatureResult = packageSignatureVerifier.VerifySignaturesAsync(pr, verifierSettings, CancellationToken.None);

                return(verifySignatureResult.Result.Valid);
            }
        }
Exemplo n.º 16
0
        public override bool CanVerifySignedPackages(SignedPackageVerifierSettings verifierSettings)
        {
#if IS_SIGNING_SUPPORTED
            // Mono support has been deprioritized, so verification on Mono is not enabled, tracking issue: https://github.com/NuGet/Home/issues/9027
            if (RuntimeEnvironmentHelper.IsMono)
            {
                return(false);
            }
            else
            {
                return(true);
            }
#else
            return(false);
#endif
        }
Exemplo n.º 17
0
        public async Task GetTrustResultAsync_WithUnavailableRevocationInformationInRequireMode_Warns()
        {
            // Arrange
            var setting = SignedPackageVerifierSettings.GetRequireModeDefaultPolicy();

            // Act & Assert
            var matchingIssues = await VerifyUnavailableRevocationInfo(
                SignatureVerificationStatus.Valid,
                LogLevel.Warning,
                setting);

            Assert.Equal(2, matchingIssues.Count);

            AssertOfflineRevocation(matchingIssues, LogLevel.Warning);
            AssertRevocationStatusUnknown(matchingIssues, LogLevel.Warning);
        }
Exemplo n.º 18
0
        public void InstallPackagesFromVSExtensionRepository(string extensionId, bool isPreUnzipped, bool skipAssemblyReferences, bool ignoreDependencies, Project project, IDictionary <string, string> packageVersions)
        {
            if (string.IsNullOrEmpty(extensionId))
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(extensionId));
            }

            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            if (!packageVersions.Any())
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(packageVersions));
            }

            RunJTFWithCorrectContext(project, () =>
            {
                var repoProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider);
                repoProvider.AddFromExtension(_sourceRepositoryProvider, extensionId);

                var toInstall = GetIdentitiesFromDict(packageVersions);

                // Skip assembly references and disable binding redirections should be done together
                var disableBindingRedirects = skipAssemblyReferences;

                var projectContext        = new VSAPIProjectContext(skipAssemblyReferences, disableBindingRedirects);
                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
                var logger = new LoggerAdapter(projectContext);
                projectContext.PackageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    logger,
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetClientPolicy(_settings, logger));

                return(InstallInternalAsync(
                           project,
                           toInstall,
                           repoProvider,
                           projectContext,
                           includePrerelease: false,
                           ignoreDependencies: ignoreDependencies,
                           token: CancellationToken.None));
            });
        }
        public async Task VerifySignaturesAsync_WithBasicSignedCms_SucceedsAsync()
        {
            var settings = new SignedPackageVerifierSettings(
                allowUnsigned: false,
                allowIllegal: false,
                allowUntrusted: false,
                allowIgnoreTimestamp: false,
                allowMultipleTimestamps: true,
                allowNoTimestamp: true,
                allowUnknownRevocation: false,
                allowNoClientCertificateList: true,
                allowNoRepositoryCertificateList: true,
                alwaysVerifyCountersignature: false);

            using (var directory = TestDirectory.Create())
                using (var certificate = new X509Certificate2(_trustedTestCert.Source.Cert))
                {
                    var packageContext      = new SimpleTestPackageContext();
                    var unsignedPackageFile = await packageContext.CreateAsFileAsync(directory, "Package.nupkg");

                    var signedPackageFile = await SignedArchiveTestUtility.SignPackageFileWithBasicSignedCmsAsync(
                        directory,
                        unsignedPackageFile,
                        certificate);

                    var verifier = new PackageSignatureVerifier(_trustProviders);

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

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

                        Assert.Equal(1, result.Results.Count);

                        var signedPackageVerificationResult = (SignedPackageVerificationResult)result.Results[0];
                        var signer = signedPackageVerificationResult.Signature.SignedCms.SignerInfos[0];

                        Assert.Equal(0, signer.SignedAttributes.Count);
                        Assert.Equal(0, signer.UnsignedAttributes.Count);

                        Assert.Equal(0, resultsWithErrors.Count());
                        Assert.Equal(0, totalErrorIssues.Count());
                    }
                }
        }
Exemplo n.º 20
0
        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 ConstructorWithLists_InitializesProperties(
            bool boolValue,
            VerificationTarget verificationTarget,
            SignaturePlacement signaturePlacement,
            SignatureVerificationBehavior signatureVerificationBehavior,
            RevocationMode revocationMode)
        {
            // Arrange
            var repoList   = new List <CertificateHashAllowListEntry>();
            var clientList = new List <CertificateHashAllowListEntry>();

            // Act
            var settings = new SignedPackageVerifierSettings(
                allowUnsigned: boolValue,
                allowIllegal: boolValue,
                allowUntrusted: boolValue,
                allowIgnoreTimestamp: boolValue,
                allowMultipleTimestamps: boolValue,
                allowNoTimestamp: boolValue,
                allowUnknownRevocation: boolValue,
                reportUnknownRevocation: boolValue,
                allowNoRepositoryCertificateList: boolValue,
                allowNoClientCertificateList: boolValue,
                verificationTarget: verificationTarget,
                signaturePlacement: signaturePlacement,
                repositoryCountersignatureVerificationBehavior: signatureVerificationBehavior,
                revocationMode: revocationMode,
                repoAllowListEntries: repoList,
                clientAllowListEntries: clientList);

            // Assert
            settings.AllowUnsigned.Should().Be(boolValue);
            settings.AllowIllegal.Should().Be(boolValue);
            settings.AllowUntrusted.Should().Be(boolValue);
            settings.AllowIgnoreTimestamp.Should().Be(boolValue);
            settings.AllowMultipleTimestamps.Should().Be(boolValue);
            settings.AllowNoTimestamp.Should().Be(boolValue);
            settings.AllowUnknownRevocation.Should().Be(boolValue);
            settings.AllowNoRepositoryCertificateList.Should().Be(boolValue);
            settings.AllowNoClientCertificateList.Should().Be(boolValue);
            settings.RepositoryCountersignatureVerificationBehavior.Should().Be(signatureVerificationBehavior);
            settings.RevocationMode.Should().Be(revocationMode);
            settings.RepositoryCertificateList.Should().BeSameAs(repoList);
            settings.ClientCertificateList.Should().BeSameAs(clientList);
        }
            internal static async Task <GetTrustResultAsyncTest> CreateAsync(SignedPackageVerifierSettings settings, X509Certificate2 certificate)
            {
                using (var certificateClone = new X509Certificate2(certificate))
                {
                    var directory           = TestDirectory.Create();
                    var packageContext      = new SimpleTestPackageContext();
                    var unsignedPackageFile = packageContext.CreateAsFile(directory, "package.nupkg");
                    var signedPackageFile   = await SignedArchiveTestUtility.SignPackageFileWithBasicSignedCmsAsync(
                        directory,
                        unsignedPackageFile,
                        certificateClone);

                    var package   = new SignedPackageArchive(signedPackageFile.OpenRead(), new MemoryStream());
                    var signature = await package.GetSignatureAsync(CancellationToken.None);

                    return(new GetTrustResultAsyncTest(directory, package, signature, settings));
                }
            }
Exemplo n.º 23
0
        public async Task VerifySignaturesAsync_SettingsRequireCheckCountersiganture_WithValidPrimarySignatureAndValidCountersignature_Succeeds()
        {
            // Arrange
            var nupkg            = new SimpleTestPackageContext();
            var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync();

            var settings = new SignedPackageVerifierSettings(
                allowUnsigned: false,
                allowIllegal: false,
                allowUntrusted: false,
                allowIgnoreTimestamp: true,
                allowMultipleTimestamps: true,
                allowNoTimestamp: true,
                allowUnknownRevocation: true,
                alwaysVerifyCountersignature: true,
                allowNoClientCertificateList: true,
                allowNoRepositoryCertificateList: true);

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

                        var countersignedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(repoTestCertificate, signedPackagePath, dir, new Uri("https://v3serviceIndex.test/api/index.json"), timestampService.Url);

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

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

                            // Assert
                            result.Valid.Should().BeTrue();
                            resultsWithErrors.Count().Should().Be(0);
                        }
                    }
        }
Exemplo n.º 24
0
        public NuGetUIFactory(
            ICommonOperations commonOperations,
            INuGetUILogger logger,
            ISourceControlManagerProvider sourceControlManagerProvider)
        {
            var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

            ProjectContext = new NuGetUIProjectContext(
                commonOperations,
                logger,
                sourceControlManagerProvider);

            ProjectContext.PackageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv2,
                PackageExtractionBehavior.XmlDocFileSaveMode,
                new LoggerAdapter(ProjectContext),
                signedPackageVerifier,
                SignedPackageVerifierSettings.GetDefault());
        }
Exemplo n.º 25
0
        private async Task PushPackageToFileSystem(Uri sourceUri,
                                                   string pathToPackage,
                                                   ILogger log,
                                                   CancellationToken token)
        {
            var             root            = sourceUri.LocalPath;
            PackageIdentity packageIdentity = null;

            using (var reader = new PackageArchiveReader(pathToPackage))
            {
                packageIdentity = reader.GetIdentity();
            }

            if (IsV2LocalRepository(root))
            {
                var pathResolver    = new PackagePathResolver(root, useSideBySidePaths: true);
                var packageFileName = pathResolver.GetPackageFileName(packageIdentity);

                var fullPath = Path.Combine(root, packageFileName);
                File.Copy(pathToPackage, fullPath, overwrite: true);
            }
            else
            {
                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

                var packageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv3,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    log,
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetClientPolicy(Settings, log));

                var context = new OfflineFeedAddContext(pathToPackage,
                                                        root,
                                                        log,
                                                        throwIfSourcePackageIsInvalid: true,
                                                        throwIfPackageExistsAndInvalid: false,
                                                        throwIfPackageExists: false,
                                                        extractionContext: packageExtractionContext);

                await OfflineFeedUtility.AddPackageToSource(context, token);
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Asynchronously copies satellite files.
        /// </summary>
        /// <param name="packageIdentity">A package identity.</param>
        /// <param name="nuGetProjectContext">A NuGet project context.</param>
        /// <param name="token">A cancellation token.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result (<see cref="Task{TResult}.Result" />) returns a <see cref="bool" />
        /// indication successfulness of the operation.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="packageIdentity" />
        /// is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="nuGetProjectContext" />
        /// is <c>null</c>.</exception>
        /// <exception cref="OperationCanceledException">Thrown if <paramref name="token" />
        /// is cancelled.</exception>
        public async Task <bool> CopySatelliteFilesAsync(
            PackageIdentity packageIdentity,
            INuGetProjectContext nuGetProjectContext,
            CancellationToken token)
        {
            if (packageIdentity == null)
            {
                throw new ArgumentNullException(nameof(packageIdentity));
            }

            if (nuGetProjectContext == null)
            {
                throw new ArgumentNullException(nameof(nuGetProjectContext));
            }

            token.ThrowIfCancellationRequested();

            var packageExtractionContext = nuGetProjectContext.PackageExtractionContext;

            if (packageExtractionContext == null)
            {
                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

                packageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    new LoggerAdapter(nuGetProjectContext),
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetDefault());
            }

            var copiedSatelliteFiles = await PackageExtractor.CopySatelliteFilesAsync(
                packageIdentity,
                PackagePathResolver,
                GetPackageSaveMode(nuGetProjectContext),
                packageExtractionContext,
                token);

            FileSystemUtility.PendAddFiles(copiedSatelliteFiles, Root, nuGetProjectContext);

            return(copiedSatelliteFiles.Any());
        }
Exemplo n.º 27
0
 public TestRestoreRequest(
     PackageSpec project,
     IEnumerable <SourceRepository> sources,
     string packagesDirectory,
     IEnumerable <string> fallbackPackageFolders,
     ILogger log) : this(
         project,
         sources,
         packagesDirectory,
         fallbackPackageFolders,
         new TestSourceCacheContext(),
         new PackageExtractionContext(
             PackageSaveMode.Defaultv3,
             PackageExtractionBehavior.XmlDocFileSaveMode,
             log,
             new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders()),
             SignedPackageVerifierSettings.GetDefault()),
         log)
 {
 }
        public async Task GetTrustResultAsync_WithUnavailableRevocationInformationAndAllowUntrusted_Warns()
        {
            // Arrange
            var setting = new SignedPackageVerifierSettings(
                allowUnsigned: false,
                allowUntrusted: true,
                allowUntrustedSelfSignedCertificate: false,
                allowIgnoreTimestamp: false,
                allowMultipleTimestamps: false,
                allowNoTimestamp: false,
                allowUnknownRevocation: true);

            // Act & Assert
            var matchingIssues = await VerifyUnavailableRevocationInfo(
                SignatureVerificationStatus.Trusted,
                LogLevel.Warning,
                setting);

            Assert.Empty(matchingIssues);
        }
Exemplo n.º 29
0
        /// <summary>
        /// This constructor is just used for testing.
        /// </summary>
        public VsPathContextProvider(
            ISettings settings,
            IVsSolutionManager solutionManager,
            NuGet.Common.ILogger logger,
            Func <BuildIntegratedNuGetProject, Task <LockFile> > getLockFileOrNullAsync)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            if (solutionManager == null)
            {
                throw new ArgumentNullException(nameof(solutionManager));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _settings               = new Lazy <ISettings>(() => settings);
            _solutionManager        = new Lazy <IVsSolutionManager>(() => solutionManager);
            _logger                 = new Lazy <NuGet.Common.ILogger>(() => logger);
            _getLockFileOrNullAsync = getLockFileOrNullAsync ?? BuildIntegratedProjectUtility.GetLockFileOrNull;

            _projectContext = new Lazy <INuGetProjectContext>(() => {
                var projectContext = new VSAPIProjectContext();

                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
                var adapterLogger         = new LoggerAdapter(projectContext);
                projectContext.PackageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    adapterLogger,
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetClientPolicy(settings, adapterLogger));

                return(projectContext);
            });
        }
            public async Task VerifySignaturesAsync_SettingsRequireTimestamp_NoTimestamp_FailsAsync()
            {
                // Arrange
                var nupkg    = new SimpleTestPackageContext();
                var settings = new SignedPackageVerifierSettings(
                    allowUnsigned: false,
                    allowIllegal: false,
                    allowUntrusted: false,
                    allowIgnoreTimestamp: false,
                    allowMultipleTimestamps: true,
                    allowNoTimestamp: false,
                    allowUnknownRevocation: false,
                    reportUnknownRevocation: true,
                    verificationTarget: VerificationTarget.All,
                    signaturePlacement: SignaturePlacement.Any,
                    repositoryCountersignatureVerificationBehavior: SignatureVerificationBehavior.IfExistsAndIsNecessary,
                    revocationMode: RevocationMode.Online);

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

                        var verifier = new PackageSignatureVerifier(_trustProviders);

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

                            IEnumerable <PackageVerificationResult> resultsWithErrors = result.Results.Where(r => r.GetErrorIssues().Any());
                            IEnumerable <ILogMessage> totalErrorIssues = resultsWithErrors.SelectMany(r => r.GetErrorIssues());

                            // Assert
                            result.IsValid.Should().BeFalse();
                            resultsWithErrors.Count().Should().Be(1);
                            totalErrorIssues.Count().Should().Be(1);
                            totalErrorIssues.First().Code.Should().Be(NuGetLogCode.NU3027);
                        }
                    }
            }