Esempio n. 1
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 verificationProviders = SignatureVerificationProviderFactory.GetSignatureVerificationProviders();
                var verifier = new PackageSignatureVerifier(verificationProviders, SignedPackageVerifierSettings.VerifyCommandDefaultPolicy);


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

            return(errorCount == 0 ? SuccessCode : FailureCode);
        }
        private async Task PushPackage(string packagePath,
                                       string source,
                                       string apiKey,
                                       bool noServiceEndpoint,
                                       TimeSpan requestTimeout,
                                       ILogger log,
                                       CancellationToken token)
        {
            var sourceUri = UriUtility.CreateSourceUri(source);

            if (string.IsNullOrEmpty(apiKey) && !sourceUri.IsFile)
            {
                log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                             Strings.NoApiKeyFound,
                                             GetSourceDisplayName(source)));
            }

            var packagesToPush = LocalFolderUtility.ResolvePackageFromPath(packagePath);

            LocalFolderUtility.EnsurePackageFileExists(packagePath, packagesToPush);

            foreach (var packageToPush in packagesToPush)
            {
                await PushPackageCore(source, apiKey, packageToPush, noServiceEndpoint, requestTimeout, log, token);
            }
        }
Esempio n. 3
0
        private async Task PushPackage(string packagePath,
                                       string source,
                                       string apiKey,
                                       bool noServiceEndpoint,
                                       bool skipDuplicate,
                                       TimeSpan requestTimeout,
                                       ILogger log,
                                       CancellationToken token)
        {
            var nupkgsToPush = LocalFolderUtility.ResolvePackageFromPath(packagePath, isSnupkg: false);

            if (!(nupkgsToPush != null && nupkgsToPush.Any()))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                          Strings.UnableToFindFile,
                                                          packagePath));
            }

            var sourceUri = UriUtility.CreateSourceUri(source);

            if (string.IsNullOrEmpty(apiKey) && !sourceUri.IsFile)
            {
                log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                             Strings.NoApiKeyFound,
                                             GetSourceDisplayName(source)));
            }

            await PushAll(source, apiKey, noServiceEndpoint, skipDuplicate, requestTimeout, log, packagesToPush : nupkgsToPush, token);
        }
        protected IEnumerable <string> GetPackages()
        {
            // resolve path into multiple packages if needed.
            var packagesToSign = LocalFolderUtility.ResolvePackageFromPath(Arguments[0]);

            LocalFolderUtility.EnsurePackageFileExists(Arguments[0], packagesToSign);

            return(packagesToSign);
        }
Esempio n. 5
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. 6
0
        public async Task <int> ExecuteCommandAsync(SignArgs signArgs)
        {
            // resolve path into multiple packages if needed.
            IEnumerable <string> packagesToSign = signArgs.PackagePaths.SelectMany(packagePath =>
            {
                IEnumerable <string> packages = LocalFolderUtility.ResolvePackageFromPath(packagePath);
                LocalFolderUtility.EnsurePackageFileExists(packagePath, packages);
                return(packages);
            });

            var success = true;

            X509Certificate2 cert = null;

            try
            {
                cert = await GetCertificateAsync(signArgs);
            }
            catch (Exception e)
            {
                success = false;
                ExceptionUtilities.LogException(e, signArgs.Logger);
            }

            if (success)
            {
                signArgs.Logger.LogInformation(Environment.NewLine);
                signArgs.Logger.LogInformation(Strings.SignCommandDisplayCertificate);
                signArgs.Logger.LogInformation(CertificateUtility.X509Certificate2ToString(cert, HashAlgorithmName.SHA256));

                if (!string.IsNullOrEmpty(signArgs.Timestamper))
                {
                    signArgs.Logger.LogInformation(Strings.SignCommandDisplayTimestamper);
                    signArgs.Logger.LogInformation(signArgs.Timestamper);
                }

                if (!string.IsNullOrEmpty(signArgs.OutputDirectory))
                {
                    signArgs.Logger.LogInformation(Strings.SignCommandOutputPath);
                    signArgs.Logger.LogInformation(signArgs.OutputDirectory);
                }

                using (var signRequest = new AuthorSignPackageRequest(cert, signArgs.SignatureHashAlgorithm, signArgs.TimestampHashAlgorithm))
                {
                    return(await ExecuteCommandAsync(
                               packagesToSign,
                               signRequest,
                               signArgs.Timestamper,
                               signArgs.Logger,
                               signArgs.OutputDirectory,
                               signArgs.Overwrite,
                               signArgs.Token));
                }
            }

            return(success ? 0 : 1);
        }
        public async Task <bool> SignAsync(string packagePath, string outputPath, string timestampUrl, Uri v3ServiceIndex, IReadOnlyList <string> packageOwners,
                                           SignatureType signatureType, HashAlgorithmName signatureHashAlgorithm, HashAlgorithmName timestampHashAlgorithm,
                                           bool overwrite, X509Certificate2 publicCertificate, System.Security.Cryptography.RSA rsa, CancellationToken cancellationToken = default)
        {
            var packagesToSign = LocalFolderUtility.ResolvePackageFromPath(packagePath);

            var signatureProvider = new KeyVaultSignatureProvider(rsa, new Rfc3161TimestampProvider(new Uri(timestampUrl)));

            SignPackageRequest request = null;

            if (signatureType == SignatureType.Author)
            {
                request = new AuthorSignPackageRequest(publicCertificate, signatureHashAlgorithm, timestampHashAlgorithm);
            }
            else if (signatureType == SignatureType.Repository)
            {
                request = new RepositorySignPackageRequest(publicCertificate, signatureHashAlgorithm, timestampHashAlgorithm, v3ServiceIndex, packageOwners);
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(signatureType));
            }

            string originalPackageCopyPath = null;

            foreach (var package in packagesToSign)
            {
                cancellationToken.ThrowIfCancellationRequested();
                logger.LogInformation($"{nameof(SignAsync)} [{package}]: Begin Signing {Path.GetFileName(package)}");
                try
                {
                    originalPackageCopyPath = CopyPackage(package);

                    using var options = SigningOptions.CreateFromFilePaths(originalPackageCopyPath, outputPath, overwrite, signatureProvider, new NuGetLogger(logger, package));
                    await SigningUtility.SignAsync(options, request, cancellationToken);
                }
                catch (Exception e)
                {
                    logger.LogError(e, e.Message);
                    return(false);
                }
                finally
                {
                    try
                    {
                        FileUtility.Delete(originalPackageCopyPath);
                    }
                    catch
                    {
                    }

                    logger.LogInformation($"{nameof(SignAsync)} [{package}]: End Signing {Path.GetFileName(package)}");
                }
            }

            return(true);
        }
Esempio n. 8
0
        private async Task PushSymbolsPath(string packagePath,
                                           string symbolSource,
                                           string apiKey,
                                           bool noServiceEndpoint,
                                           bool skipDuplicate,
                                           SymbolPackageUpdateResourceV3 symbolPackageUpdateResource,
                                           TimeSpan requestTimeout,
                                           ILogger log,
                                           bool explicitSymbolsPush,
                                           CancellationToken token)
        {
            bool isSymbolEndpointSnupkgCapable = symbolPackageUpdateResource != null;
            // Get the symbol package for this package
            string symbolPackagePath = GetSymbolsPath(packagePath, isSymbolEndpointSnupkgCapable);

            IEnumerable <string> symbolsToPush = LocalFolderUtility.ResolvePackageFromPath(symbolPackagePath, isSnupkg: isSymbolEndpointSnupkgCapable);
            bool symbolsPathResolved           = symbolsToPush != null && symbolsToPush.Any();

            //No files were resolved.
            if (!symbolsPathResolved)
            {
                if (explicitSymbolsPush)
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                              Strings.UnableToFindFile,
                                                              packagePath));
                }
            }
            else
            {
                Uri symbolSourceUri = UriUtility.CreateSourceUri(symbolSource);

                // See if the api key exists
                if (string.IsNullOrEmpty(apiKey) && !symbolSourceUri.IsFile)
                {
                    log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                                 Strings.Warning_SymbolServerNotConfigured,
                                                 Path.GetFileName(symbolPackagePath),
                                                 Strings.DefaultSymbolServer));
                }

                foreach (string packageToPush in symbolsToPush)
                {
                    await PushPackageCore(symbolSource, apiKey, packageToPush, noServiceEndpoint, skipDuplicate, requestTimeout, log, token);
                }
            }
        }
        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);
        }
Esempio n. 10
0
        public async Task <int> ExecuteCommandAsync(SignArgs signArgs)
        {
            // resolve path into multiple packages if needed.
            var packagesToSign = LocalFolderUtility.ResolvePackageFromPath(signArgs.PackagePath);

            LocalFolderUtility.EnsurePackageFileExists(signArgs.PackagePath, packagesToSign);

            var cert = await GetCertificateAsync(signArgs);

            signArgs.Logger.LogInformation(Environment.NewLine);
            signArgs.Logger.LogInformation(Strings.SignCommandDisplayCertificate);
            signArgs.Logger.LogInformation(CertificateUtility.X509Certificate2ToString(cert, HashAlgorithmName.SHA256));

            if (!string.IsNullOrEmpty(signArgs.Timestamper))
            {
                signArgs.Logger.LogInformation(Strings.SignCommandDisplayTimestamper);
                signArgs.Logger.LogInformation(signArgs.Timestamper);
            }

            if (!string.IsNullOrEmpty(signArgs.OutputDirectory))
            {
                signArgs.Logger.LogInformation(Strings.SignCommandOutputPath);
                signArgs.Logger.LogInformation(signArgs.OutputDirectory);
            }

            using (var signRequest = GenerateSignPackageRequest(signArgs, cert))
            {
                return(await ExecuteCommandAsync(
                           packagesToSign,
                           signRequest,
                           signArgs.Timestamper,
                           signArgs.Logger,
                           signArgs.OutputDirectory,
                           signArgs.Overwrite,
                           signArgs.Token));
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Push nupkgs, and if successful, push any corresponding symbols.
        /// </summary>
        /// <exception cref="ArgumentException">Thrown when any resolved file path does not exist.</exception>
        private async Task PushPackagePath(string packagePath,
                                           string source,
                                           string symbolSource, // empty to not push symbols
                                           string apiKey,
                                           Func <string, string> getSymbolApiKey,
                                           bool noServiceEndpoint,
                                           bool skipDuplicate,
                                           SymbolPackageUpdateResourceV3 symbolPackageUpdateResource,
                                           TimeSpan requestTimeout,
                                           ILogger log,
                                           CancellationToken token)
        {
            IEnumerable <string> nupkgsToPush           = LocalFolderUtility.ResolvePackageFromPath(packagePath, isSnupkg: false);
            bool alreadyWarnedSymbolServerNotConfigured = false;

            if (!(nupkgsToPush != null && nupkgsToPush.Any()))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                          Strings.UnableToFindFile,
                                                          packagePath));
            }

            Uri packageSourceUri = UriUtility.CreateSourceUri(source);

            if (string.IsNullOrEmpty(apiKey) && !packageSourceUri.IsFile)
            {
                log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                             Strings.NoApiKeyFound,
                                             GetSourceDisplayName(source)));
            }

            foreach (string nupkgToPush in nupkgsToPush)
            {
                bool packageWasPushed = await PushPackageCore(source, apiKey, nupkgToPush, noServiceEndpoint, skipDuplicate, requestTimeout, log, token);

                // Push corresponding symbols, if successful.
                if (packageWasPushed && !string.IsNullOrEmpty(symbolSource))
                {
                    bool   isSymbolEndpointSnupkgCapable = symbolPackageUpdateResource != null;
                    string symbolPackagePath             = GetSymbolsPath(nupkgToPush, isSnupkg: isSymbolEndpointSnupkgCapable);

                    // There may not be a snupkg with the same filename. Ignore it since this isn't an explicit snupkg push.
                    if (!File.Exists(symbolPackagePath))
                    {
                        continue;
                    }

                    if (!alreadyWarnedSymbolServerNotConfigured)
                    {
                        Uri symbolSourceUri = UriUtility.CreateSourceUri(symbolSource);

                        // See if the api key exists
                        if (string.IsNullOrEmpty(apiKey) && !symbolSourceUri.IsFile)
                        {
                            log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                                         Strings.Warning_SymbolServerNotConfigured,
                                                         Path.GetFileName(symbolPackagePath),
                                                         Strings.DefaultSymbolServer));

                            alreadyWarnedSymbolServerNotConfigured = true;
                        }
                    }

                    string symbolApiKey = getSymbolApiKey(symbolSource);
                    await PushPackageCore(symbolSource, symbolApiKey, symbolPackagePath, noServiceEndpoint, skipDuplicate, requestTimeout, log, token);
                }
            }
        }
        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 <int> ExecuteCommandAsync(TrustedSignersArgs trustedSignersArgs)
        {
            var logger          = trustedSignersArgs.Logger ?? NullLogger.Instance;
            var actionsProvider = new TrustedSignerActionsProvider(_trustedSignersProvider, logger);

            switch (trustedSignersArgs.Action)
            {
            case TrustedSignersAction.List:
                ValidateListArguments(trustedSignersArgs);

                await ListAllTrustedSignersAsync(logger);

                break;

            case TrustedSignersAction.Add:
                ValidateNameExists(trustedSignersArgs.Name);

                var isPackagePathProvided  = !string.IsNullOrEmpty(trustedSignersArgs.PackagePath);
                var isServiceIndexProvided = !string.IsNullOrEmpty(trustedSignersArgs.ServiceIndex);
                var isFingerprintProvided  = !string.IsNullOrEmpty(trustedSignersArgs.CertificateFingerprint);
                var isAlgorithmProvided    = !string.IsNullOrEmpty(trustedSignersArgs.FingerprintAlgorithm);

                if (isPackagePathProvided)
                {
#if IS_DESKTOP
                    if (isServiceIndexProvided || isFingerprintProvided || isAlgorithmProvided)
                    {
                        throw new CommandLineArgumentCombinationException(string.Format(CultureInfo.CurrentCulture, Strings.Error_CouldNotAdd, Strings.Error_InvalidCombinationOfArguments));
                    }

                    if (!(trustedSignersArgs.Repository ^ trustedSignersArgs.Author))
                    {
                        throw new CommandLineArgumentCombinationException(string.Format(CultureInfo.CurrentCulture, Strings.Error_NoSignatureTrustedForPackage, trustedSignersArgs.PackagePath));
                    }

                    var trustTarget = VerificationTarget.None;
                    if (trustedSignersArgs.Author)
                    {
                        if (!trustedSignersArgs.Repository && trustedSignersArgs.Owners != null && trustedSignersArgs.Owners.Any())
                        {
                            throw new CommandLineArgumentCombinationException(Strings.Error_CannotTrustOwnersForAuthor);
                        }

                        trustTarget |= VerificationTarget.Author;
                    }

                    if (trustedSignersArgs.Repository)
                    {
                        trustTarget |= VerificationTarget.Repository;
                    }

                    if (trustTarget == VerificationTarget.None)
                    {
                        trustTarget = VerificationTarget.Unknown;
                    }

                    var packagesToTrust = LocalFolderUtility.ResolvePackageFromPath(trustedSignersArgs.PackagePath);
                    LocalFolderUtility.EnsurePackageFileExists(trustedSignersArgs.PackagePath, packagesToTrust);

                    foreach (var package in packagesToTrust)
                    {
                        using (var packageReader = new PackageArchiveReader(package))
                        {
                            await actionsProvider.AddTrustedSignerAsync(
                                trustedSignersArgs.Name,
                                packageReader,
                                trustTarget,
                                trustedSignersArgs.AllowUntrustedRoot,
                                trustedSignersArgs.Owners,
                                CancellationToken.None);
                        }
                    }

                    break;
#else
                    throw new NotSupportedException();
#endif
                }

                if (isServiceIndexProvided)
                {
                    if (isFingerprintProvided || isAlgorithmProvided || trustedSignersArgs.Author || trustedSignersArgs.Repository)
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.Error_CouldNotAdd, Strings.Error_InvalidCombinationOfArguments));
                    }

                    var serviceIndex = ValidateAndParseV3ServiceIndexUrl(trustedSignersArgs.ServiceIndex);

                    await actionsProvider.AddTrustedRepositoryAsync(
                        trustedSignersArgs.Name,
                        serviceIndex,
                        trustedSignersArgs.Owners,
                        CancellationToken.None);

                    break;
                }

                if (isFingerprintProvided)
                {
                    if (trustedSignersArgs.Owners != null && trustedSignersArgs.Owners.Any())
                    {
                        throw new ArgumentException(Strings.Error_CannotTrustOwnersForAuthor);
                    }

                    var hashAlgorithm = ValidateAndParseFingerprintAlgorithm(trustedSignersArgs.FingerprintAlgorithm);

                    actionsProvider.AddOrUpdateTrustedSigner(
                        trustedSignersArgs.Name,
                        trustedSignersArgs.CertificateFingerprint,
                        hashAlgorithm,
                        trustedSignersArgs.AllowUntrustedRoot);

                    break;
                }

                if (isAlgorithmProvided || trustedSignersArgs.Author || trustedSignersArgs.Repository)
                {
                    throw new CommandLineArgumentCombinationException(string.Format(CultureInfo.CurrentCulture, Strings.Error_CouldNotAdd, Strings.Error_InvalidCombinationOfArguments));
                }

                if (_packageSourceProvider == null)
                {
                    throw new ArgumentException(Strings.Error_NoSourcesInformation);
                }

                var packageSource = _packageSourceProvider.GetPackageSourceByName(trustedSignersArgs.Name);
                if (packageSource == null || string.IsNullOrEmpty(packageSource.Source))
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.Error_UnavailableSource, trustedSignersArgs.Name));
                }

                var sourceServiceIndex = ValidateAndParseV3ServiceIndexUrl(packageSource.Source);

                await actionsProvider.AddTrustedRepositoryAsync(
                    trustedSignersArgs.Name,
                    sourceServiceIndex,
                    trustedSignersArgs.Owners,
                    CancellationToken.None);


                break;

            case TrustedSignersAction.Remove:
                ValidateRemoveArguments(trustedSignersArgs);

                await RemoveTrustedSignerAsync(trustedSignersArgs.Name, logger);

                break;

            case TrustedSignersAction.Sync:
                ValidateSyncArguments(trustedSignersArgs);

                await actionsProvider.SyncTrustedRepositoryAsync(trustedSignersArgs.Name, CancellationToken.None);

                break;
            }

            return(SuccessCode);
        }
Esempio n. 14
0
        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);

            var allPackagesVerified = true;

            try
            {
                var result           = 0;
                var packagesToVerify = LocalFolderUtility.ResolvePackageFromPath(file);

                foreach (var packageFile in packagesToVerify)
                {
                    using var package = new PackageArchiveReader(packageFile);
                    var verificationResult = await verifier.VerifySignaturesAsync(package, SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy(), CancellationToken.None);

                    if (verificationResult.IsValid)
                    {
                        allPackagesVerified = true;
                    }
                    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;
                        }
                        allPackagesVerified = false;
                    }
                }
            }
            catch (Exception e)
            {
                logger.LogError(e, e.Message);
                return(false);
            }

            return(allPackagesVerified);
        }