public void GetVerifyCommandDefaultPolicy_InitializesProperties()
        {
            // Arrange
            var repoList   = new List <CertificateHashAllowListEntry>();
            var clientList = new List <CertificateHashAllowListEntry>();

            // Act
            var settings = SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy(repoList, clientList);

            // Assert
            settings.AllowUnsigned.Should().Be(false);
            settings.AllowIllegal.Should().Be(false);
            settings.AllowUntrusted.Should().Be(false);
            settings.AllowIgnoreTimestamp.Should().Be(false);
            settings.AllowMultipleTimestamps.Should().Be(true);
            settings.AllowNoTimestamp.Should().Be(true);
            settings.AllowUnknownRevocation.Should().Be(true);
            settings.ReportUnknownRevocation.Should().Be(true);
            settings.AllowNoRepositoryCertificateList.Should().Be(true);
            settings.AllowNoClientCertificateList.Should().Be(true);
            settings.VerificationTarget.Should().Be(VerificationTarget.All);
            settings.SignaturePlacement.Should().Be(SignaturePlacement.Any);
            settings.RepositoryCountersignatureVerificationBehavior.Should().Be(SignatureVerificationBehavior.IfExists);
            settings.RepositoryCertificateList.Should().BeSameAs(repoList);
            settings.ClientCertificateList.Should().BeSameAs(clientList);
        }
        public void GetVerifyCommandDefaultPolicy_InitializesProperties(string revocationModeEnvVar, RevocationMode expectedRevocationMode)
        {
            // Arrange
            if (revocationModeEnvVar != null)
            {
                Environment.SetEnvironmentVariable(RevocationModeEnvVar, revocationModeEnvVar);
            }

            // Act
            var settings = SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy();

            // Assert
            settings.AllowUnsigned.Should().Be(false);
            settings.AllowIllegal.Should().Be(false);
            settings.AllowUntrusted.Should().Be(false);
            settings.AllowIgnoreTimestamp.Should().Be(false);
            settings.AllowMultipleTimestamps.Should().Be(true);
            settings.AllowNoTimestamp.Should().Be(true);
            settings.AllowUnknownRevocation.Should().Be(true);
            settings.ReportUnknownRevocation.Should().Be(true);
            settings.VerificationTarget.Should().Be(VerificationTarget.All);
            settings.SignaturePlacement.Should().Be(SignaturePlacement.Any);
            settings.RepositoryCountersignatureVerificationBehavior.Should().Be(SignatureVerificationBehavior.IfExists);
            settings.RevocationMode.Should().Be(expectedRevocationMode);

            Environment.SetEnvironmentVariable(RevocationModeEnvVar, string.Empty);
        }
Esempio n. 3
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 = verifyArgs.PackagePaths.SelectMany(packagePath =>
                {
                    var packages = LocalFolderUtility.ResolvePackageFromPath(packagePath);
                    LocalFolderUtility.EnsurePackageFileExists(packagePath, packages);
                    return(packages);
                });

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

                var verifierSettings      = SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy();
                var verificationProviders = new List <ISignatureVerificationProvider>()
                {
                    new IntegrityVerificationProvider(),
                    new SignatureTrustAndValidityVerificationProvider()
                };

                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);
        }
Esempio n. 4
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));
        }
        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());
        }
Esempio n. 6
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);
            }
        }
        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(clientAllowListEntries: allowListEntries);
                var verificationProviders = SignatureVerificationProviderFactory.GetSignatureVerificationProviders();
                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 GetTrustResultAsync_WithTimestampChainingToUntrustedRoot_NotAllowIgnoreTimestamp_FailAsync()
        {
            using (var nupkgStream = new MemoryStream(GetResource("UntrustedTimestampPackage.nupkg")))
                using (var package = new PackageArchiveReader(nupkgStream, leaveStreamOpen: false))
                {
                    var verifier = new PackageSignatureVerifier(_trustProviders);

                    // Act
                    var result = await verifier.VerifySignaturesAsync(package, SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy(), CancellationToken.None);

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

                    // Assert
                    result.Valid.Should().BeFalse();
                    resultsWithErrors.Count().Should().BeGreaterOrEqualTo(1);
                    totalErrorIssues.Count().Should().BeGreaterOrEqualTo(1);
                    totalErrorIssues[1].Code.Should().Be(NuGetLogCode.NU3028);
                    totalErrorIssues[1].Message.Should().Contain("A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider");
                }
        }
Esempio n. 9
0
        private bool IsSigned(string path)
        {
            IEnumerable <ISignatureVerificationProvider> providers = SignatureVerificationProviderFactory.GetSignatureVerificationProviders();
            var packageSignatureVerifier = new PackageSignatureVerifier(providers);

            var allowListEntries = new List <CertificateHashAllowListEntry>();

            allowListEntries.Add(new CertificateHashAllowListEntry(VerificationTarget.Author | VerificationTarget.Repository,
                                                                   SignaturePlacement.PrimarySignature, _fingerPrint, HashAlgorithmName.SHA256));

            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);
            }
        }
Esempio n. 10
0
        public void GetVerifyCommandDefaultPolicy_InitializesProperties()
        {
            // Arrange
            var repoList   = new List <CertificateHashAllowListEntry>();
            var clientList = new List <CertificateHashAllowListEntry>();

            // Act
            var settings = SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy(repoList, clientList);

            // Assert
            settings.AllowUnsigned.Should().Be(false);
            settings.AllowIllegal.Should().Be(false);
            settings.AllowUntrusted.Should().Be(false);
            settings.AllowUntrustedSelfIssuedCertificate.Should().Be(true);
            settings.AllowIgnoreTimestamp.Should().Be(false);
            settings.AllowMultipleTimestamps.Should().Be(true);
            settings.AllowNoTimestamp.Should().Be(true);
            settings.AllowUnknownRevocation.Should().Be(true);
            settings.AllowNoRepositoryCertificateList.Should().Be(true);
            settings.AllowNoClientCertificateList.Should().Be(true);
            settings.RepositoryCertificateList.Should().BeSameAs(repoList);
            settings.ClientCertificateList.Should().BeSameAs(clientList);
        }
Esempio n. 11
0
        public async Task GetTrustResultAsync_WithSignedTimestampedCountersignedAndCountersignatureTimestampedPackage_Succeeds()
        {
            // Arrange
            var nupkg            = new SimpleTestPackageContext();
            var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync();

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

                            var repositorySignedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(
                                counterCertificate,
                                signedPackagePath,
                                dir,
                                new Uri("https://v3ServiceIndex.test/api/index"),
                                timestampService.Url);

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

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

                                // Assert
                                result.Valid.Should().BeTrue();
                                resultsWithErrors.Count().Should().Be(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))
            {
                if (!IsSignatureVerifyCommandSupported())
                {
                    verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_NotSupported));
                    return(FailureCode);
                }

                var packagesToVerify = verifyArgs.PackagePaths.SelectMany(packagePath =>
                {
                    var packages = LocalFolderUtility.ResolvePackageFromPath(packagePath);
                    LocalFolderUtility.EnsurePackageFileExists(packagePath, packages);
                    return(packages);
                });

                ClientPolicyContext clientPolicyContext = ClientPolicyContext.GetClientPolicy(verifyArgs.Settings, verifyArgs.Logger);

                // List of values passed through --certificate-fingerprint option read
                var allowListEntries = verifyArgs.CertificateFingerprint.Select(fingerprint =>
                                                                                new CertificateHashAllowListEntry(
                                                                                    VerificationTarget.Author | VerificationTarget.Repository,
                                                                                    SignaturePlacement.PrimarySignature,
                                                                                    fingerprint,
                                                                                    _defaultFingerprintAlgorithm)).ToList();

                var verifierSettings      = SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy();
                var verificationProviders = new List <ISignatureVerificationProvider>()
                {
                    new IntegrityVerificationProvider()
                };

                // trustedSigners section >> Owners are considered here.
                verificationProviders.Add(
                    new AllowListVerificationProvider(
                        clientPolicyContext.AllowList,
                        requireNonEmptyAllowList: clientPolicyContext.Policy == SignatureValidationMode.Require,
                        emptyListErrorMessage: Strings.Error_NoClientAllowList,
                        noMatchErrorMessage: Strings.Error_NoMatchingClientCertificate));

                IEnumerable <KeyValuePair <string, HashAlgorithmName> > trustedSignerAllowUntrustedRootList = clientPolicyContext.AllowList?
                                                                                                              .Where(c => c.AllowUntrustedRoot)
                                                                                                              .Select(c => new KeyValuePair <string, HashAlgorithmName>(c.Fingerprint, c.FingerprintAlgorithm));

                // trustedSigners section >> allowUntrustedRoot set true are considered here.
                verificationProviders.Add(new SignatureTrustAndValidityVerificationProvider(trustedSignerAllowUntrustedRootList));

                // List of values passed through --certificate-fingerprint option are considered here.
                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 VerifySignatureAsync()
        {
            using (var reader = new PackageArchiveReader(_streamFactory(), false))
            {
                var signed = await reader.IsSignedAsync(CancellationToken.None);

                if (signed)
                {
                    // Check verification
                    var trustProviders = SignatureVerificationProviderFactory.GetSignatureVerificationProviders();
                    var verifier       = new PackageSignatureVerifier(trustProviders);

                    VerificationResult = await verifier.VerifySignaturesAsync(reader, SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy(), CancellationToken.None);
                }
            }
        }
        public async Task <bool> VerifyAsync(string file, StringBuilder buffer)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

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


            var trustProviders = new ISignatureVerificationProvider[]
            {
                new IntegrityVerificationProvider(),
                new SignatureTrustAndValidityVerificationProvider()
            };
            var verifier = new PackageSignatureVerifier(trustProviders);

            try
            {
                var result = 0;
                using (var package = new PackageArchiveReader(file))
                {
                    var verificationResult = await verifier.VerifySignaturesAsync(package, SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy(), CancellationToken.None);


                    if (verificationResult.IsValid)
                    {
                        return(verificationResult.IsValid);
                    }
                    else
                    {
                        var logMessages = verificationResult.Results.SelectMany(p => p.Issues).Select(p => p.AsRestoreLogMessage()).ToList();
                        foreach (var msg in logMessages)
                        {
                            buffer.AppendLine(msg.Message);
                        }
                        if (logMessages.Any(m => m.Level >= NuGet.Common.LogLevel.Warning))
                        {
                            var errors   = logMessages.Where(m => m.Level == NuGet.Common.LogLevel.Error).Count();
                            var warnings = logMessages.Where(m => m.Level == NuGet.Common.LogLevel.Warning).Count();

                            buffer.AppendLine($"Finished with {errors} errors and {warnings} warnings.");

                            result = errors;
                        }
                        return(false);
                    }
                }
            }
            catch (Exception e)
            {
                logger.LogError(e, e.Message);
                return(false);
            }
        }