|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.ComponentModel; |
| 5 | +using System.Diagnostics; |
| 6 | +using System.Runtime.InteropServices; |
| 7 | +using System.Security; |
| 8 | +using Microsoft.TemplateEngine.CommandUtils; |
| 9 | +using NuGet.Common; |
| 10 | +using NuGet.Configuration; |
| 11 | +using NuGet.Packaging; |
| 12 | +using NuGet.Packaging.Signing; |
| 13 | +using NuGet.Protocol; |
| 14 | +using NuGet.Protocol.Core.Types; |
| 15 | + |
| 16 | +namespace Microsoft.TemplateEngine.Edge.Installers.NuGet |
| 17 | +{ |
| 18 | + internal interface INuGetPackageVerifier |
| 19 | + { |
| 20 | + bool IsEnabled { get; } |
| 21 | + |
| 22 | + Task VerifyAsync(string packagePath, SourceRepository repository, ISettings settings, ILogger logger, CancellationToken cancellationToken); |
| 23 | + } |
| 24 | + |
| 25 | + internal sealed class DotnetNuGetPackageVerifier : INuGetPackageVerifier |
| 26 | + { |
| 27 | + private const string SignatureVerificationEnvironmentVariable = "DOTNET_NUGET_SIGNATURE_VERIFICATION"; |
| 28 | + |
| 29 | + public DotnetNuGetPackageVerifier() |
| 30 | + { |
| 31 | + bool? configuredValue = bool.TryParse( |
| 32 | + Environment.GetEnvironmentVariable(SignatureVerificationEnvironmentVariable), |
| 33 | + out bool shouldVerify) |
| 34 | + ? shouldVerify |
| 35 | + : null; |
| 36 | + |
| 37 | + IsEnabled = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) |
| 38 | + || configuredValue == true |
| 39 | + || (configuredValue == null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux)); |
| 40 | + } |
| 41 | + |
| 42 | + public bool IsEnabled { get; } |
| 43 | + |
| 44 | + public async Task VerifyAsync(string packagePath, SourceRepository repository, ISettings settings, ILogger logger, CancellationToken cancellationToken) |
| 45 | + { |
| 46 | + _ = packagePath ?? throw new ArgumentNullException(nameof(packagePath)); |
| 47 | + _ = repository ?? throw new ArgumentNullException(nameof(repository)); |
| 48 | + _ = settings ?? throw new ArgumentNullException(nameof(settings)); |
| 49 | + _ = logger ?? throw new ArgumentNullException(nameof(logger)); |
| 50 | + cancellationToken.ThrowIfCancellationRequested(); |
| 51 | + |
| 52 | + bool isSigned; |
| 53 | + using (var reader = new PackageArchiveReader(packagePath)) |
| 54 | + { |
| 55 | + isSigned = await reader.IsSignedAsync(cancellationToken).ConfigureAwait(false); |
| 56 | + } |
| 57 | + |
| 58 | + if (!isSigned) |
| 59 | + { |
| 60 | + ClientPolicyContext clientPolicy = ClientPolicyContext.GetClientPolicy(settings, logger); |
| 61 | + RepositorySignatureResource? repositorySignature = |
| 62 | + await repository.GetResourceAsync<RepositorySignatureResource>(cancellationToken).ConfigureAwait(false); |
| 63 | + cancellationToken.ThrowIfCancellationRequested(); |
| 64 | + if (clientPolicy.Policy == SignatureValidationMode.Require || repositorySignature?.AllRepositorySigned == true) |
| 65 | + { |
| 66 | + const string message = "The package is unsigned, but client or repository policy requires signing."; |
| 67 | + logger.LogDebug(message); |
| 68 | + throw new InvalidDataException(message); |
| 69 | + } |
| 70 | + |
| 71 | + logger.LogDebug("Accepting unsigned package under accept policy."); |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + await VerifySignedPackageAsync(packagePath, logger, cancellationToken).ConfigureAwait(false); |
| 76 | + } |
| 77 | + |
| 78 | + private static async Task VerifySignedPackageAsync(string packagePath, ILogger logger, CancellationToken cancellationToken) |
| 79 | + { |
| 80 | + cancellationToken.ThrowIfCancellationRequested(); |
| 81 | + using var process = new Process |
| 82 | + { |
| 83 | + StartInfo = new ProcessStartInfo |
| 84 | + { |
| 85 | + FileName = "dotnet", |
| 86 | + Arguments = $"nuget verify --all {ArgumentEscaper.EscapeSingleArg(packagePath)}", |
| 87 | + UseShellExecute = false, |
| 88 | + CreateNoWindow = true, |
| 89 | + RedirectStandardError = true, |
| 90 | + RedirectStandardOutput = true |
| 91 | + } |
| 92 | + }; |
| 93 | + if (!process.Start()) |
| 94 | + { |
| 95 | + throw new InvalidOperationException("Failed to start 'dotnet nuget verify'."); |
| 96 | + } |
| 97 | + |
| 98 | +#if NET |
| 99 | + Task<string> standardOutput = process.StandardOutput.ReadToEndAsync(CancellationToken.None); |
| 100 | + Task<string> standardError = process.StandardError.ReadToEndAsync(CancellationToken.None); |
| 101 | +#else |
| 102 | + Task<string> standardOutput = process.StandardOutput.ReadToEndAsync(); |
| 103 | + Task<string> standardError = process.StandardError.ReadToEndAsync(); |
| 104 | +#endif |
| 105 | + await WaitForExitAsync(process, logger, cancellationToken).ConfigureAwait(false); |
| 106 | + |
| 107 | + string output = await standardOutput.ConfigureAwait(false); |
| 108 | + string error = await standardError.ConfigureAwait(false); |
| 109 | + cancellationToken.ThrowIfCancellationRequested(); |
| 110 | + |
| 111 | + LogOutput(logger, output, LogLevel.Debug); |
| 112 | + LogOutput(logger, error, process.ExitCode == 0 ? LogLevel.Debug : LogLevel.Error); |
| 113 | + |
| 114 | + if (process.ExitCode != 0) |
| 115 | + { |
| 116 | + string command = $"{process.StartInfo.FileName} {process.StartInfo.Arguments}"; |
| 117 | + throw new SecurityException($"'{command}' failed with exit code {process.ExitCode}."); |
| 118 | + } |
| 119 | + |
| 120 | + return; |
| 121 | + |
| 122 | + static void LogOutput(ILogger logger, string output, LogLevel level) |
| 123 | + { |
| 124 | + if (!string.IsNullOrWhiteSpace(output)) |
| 125 | + { |
| 126 | + logger.Log(level, output.Trim()); |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + private static async Task WaitForExitAsync(Process process, ILogger logger, CancellationToken cancellationToken) |
| 132 | + { |
| 133 | + using (cancellationToken.Register(() => TerminateProcess(process, logger))) |
| 134 | + { |
| 135 | + // Process.WaitForExitAsync is unavailable on netstandard2.0 and net472. |
| 136 | + await Task.Run(process.WaitForExit, CancellationToken.None).ConfigureAwait(false); |
| 137 | + } |
| 138 | + |
| 139 | + return; |
| 140 | + |
| 141 | + static void TerminateProcess(Process process, ILogger logger) |
| 142 | + { |
| 143 | + try |
| 144 | + { |
| 145 | + if (!process.HasExited) |
| 146 | + { |
| 147 | + process.Kill(); |
| 148 | + } |
| 149 | + } |
| 150 | + catch (InvalidOperationException) when (process.HasExited) |
| 151 | + { |
| 152 | + // The process exited between checking HasExited and calling Kill. |
| 153 | + } |
| 154 | + catch (Win32Exception ex) |
| 155 | + { |
| 156 | + if (!process.HasExited) |
| 157 | + { |
| 158 | + logger.LogDebug($"Failed to terminate 'dotnet nuget verify': {ex}"); |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | + } |
| 163 | + } |
| 164 | +} |
0 commit comments