Skip to content

Commit

Permalink
add signature VerifySigning for dotnet tools (#39268)
Browse files Browse the repository at this point in the history
Fixes #37469

Add signature verifications for NuGet Tools
  • Loading branch information
JL03-Yue authored Aug 28, 2024
1 parent 4d4166e commit f7ddf14
Show file tree
Hide file tree
Showing 37 changed files with 413 additions and 189 deletions.
18 changes: 12 additions & 6 deletions src/Cli/dotnet/CommandFactory/CommandFactoryUsingResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ public static Command CreateDotNet(
string commandName,
IEnumerable<string> args,
NuGetFramework framework = null,
string configuration = Constants.DefaultConfiguration)
string configuration = Constants.DefaultConfiguration,
string currentWorkingDirectory = null)
{
return Create("dotnet",
new[] { commandName }.Concat(args),
framework,
configuration: configuration);
configuration: configuration,
currentWorkingDirectory);
}

/// <summary>
Expand All @@ -35,7 +37,8 @@ public static Command Create(
NuGetFramework framework = null,
string configuration = Constants.DefaultConfiguration,
string outputPath = null,
string applicationName = null)
string applicationName = null,
string currentWorkingDirectory = null)
{
return Create(
new DefaultCommandResolverPolicy(),
Expand All @@ -44,7 +47,8 @@ public static Command Create(
framework,
configuration,
outputPath,
applicationName);
applicationName,
currentWorkingDirectory);
}

public static Command Create(
Expand All @@ -54,7 +58,8 @@ public static Command Create(
NuGetFramework framework = null,
string configuration = Constants.DefaultConfiguration,
string outputPath = null,
string applicationName = null)
string applicationName = null,
string currentWorkingDirectory = null)
{
var commandSpec = CommandResolver.TryResolveCommandSpec(
commandResolverPolicy,
Expand All @@ -63,7 +68,8 @@ public static Command Create(
framework,
configuration: configuration,
outputPath: outputPath,
applicationName: applicationName);
applicationName: applicationName,
currentWorkingDirectory: currentWorkingDirectory);

if (commandSpec == null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ namespace Microsoft.DotNet.CommandFactory
{
public class DefaultCommandResolverPolicy : ICommandResolverPolicy
{
public CompositeCommandResolver CreateCommandResolver()
public CompositeCommandResolver CreateCommandResolver(string currentWorkingDirectory = null)
{
return Create();
return Create(currentWorkingDirectory);
}

public static CompositeCommandResolver Create()
public static CompositeCommandResolver Create(string currentWorkingDirectory = null)
{
var environment = new EnvironmentProvider();
var packagedCommandSpecFactory = new PackagedCommandSpecFactoryWithCliRuntime();
Expand All @@ -32,20 +32,22 @@ public static CompositeCommandResolver Create()
environment,
packagedCommandSpecFactory,
platformCommandSpecFactory,
publishedPathCommandSpecFactory);
publishedPathCommandSpecFactory,
currentWorkingDirectory);
}

public static CompositeCommandResolver CreateDefaultCommandResolver(
IEnvironmentProvider environment,
IPackagedCommandSpecFactory packagedCommandSpecFactory,
IPlatformCommandSpecFactory platformCommandSpecFactory,
IPublishedPathCommandSpecFactory publishedPathCommandSpecFactory)
IPublishedPathCommandSpecFactory publishedPathCommandSpecFactory,
string currentWorkingDirectory = null)
{
var compositeCommandResolver = new CompositeCommandResolver();

compositeCommandResolver.AddCommandResolver(new MuxerCommandResolver());
compositeCommandResolver.AddCommandResolver(new DotnetToolsCommandResolver());
compositeCommandResolver.AddCommandResolver(new LocalToolsCommandResolver());
compositeCommandResolver.AddCommandResolver(new LocalToolsCommandResolver(currentWorkingDirectory: currentWorkingDirectory));
compositeCommandResolver.AddCommandResolver(new RootedCommandResolver());
compositeCommandResolver.AddCommandResolver(
new ProjectToolsCommandResolver(packagedCommandSpecFactory, environment));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ namespace Microsoft.DotNet.CommandFactory
{
public interface ICommandResolverPolicy
{
CompositeCommandResolver CreateCommandResolver();
CompositeCommandResolver CreateCommandResolver(string currentWorkingDirectory = null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ internal class LocalToolsCommandResolver : ICommandResolver
public LocalToolsCommandResolver(
ToolManifestFinder toolManifest = null,
ILocalToolsResolverCache localToolsResolverCache = null,
IFileSystem fileSystem = null)
IFileSystem fileSystem = null,
string currentWorkingDirectory = null)
{
_toolManifest = toolManifest ?? new ToolManifestFinder(new DirectoryPath(Directory.GetCurrentDirectory()));
_toolManifest = toolManifest ?? new ToolManifestFinder(new DirectoryPath(currentWorkingDirectory ?? Directory.GetCurrentDirectory()));
_localToolsResolverCache = localToolsResolverCache ?? new LocalToolsResolverCache();
_fileSystem = fileSystem ?? new FileSystemWrapper();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace Microsoft.DotNet.CommandFactory
{
public class PathCommandResolverPolicy : ICommandResolverPolicy
{
public CompositeCommandResolver CreateCommandResolver()
public CompositeCommandResolver CreateCommandResolver(string CurrentWorkingDirectory = null)
{
return Create();
}
Expand Down
7 changes: 4 additions & 3 deletions src/Cli/dotnet/CommandFactory/CommandResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,21 @@ public static CommandSpec TryResolveCommandSpec(
NuGetFramework framework = null,
string configuration = Constants.DefaultConfiguration,
string outputPath = null,
string applicationName = null)
string applicationName = null,
string currentWorkingDirectory = null)
{
var commandResolverArgs = new CommandResolverArguments
{
CommandName = commandName,
CommandArguments = args,
Framework = framework,
ProjectDirectory = Directory.GetCurrentDirectory(),
ProjectDirectory = currentWorkingDirectory ?? Directory.GetCurrentDirectory(),
Configuration = configuration,
OutputPath = outputPath,
ApplicationName = applicationName
};

var defaultCommandResolver = commandResolverPolicy.CreateCommandResolver();
var defaultCommandResolver = commandResolverPolicy.CreateCommandResolver(currentWorkingDirectory);

return defaultCommandResolver.Resolve(commandResolverArgs);
}
Expand Down
6 changes: 4 additions & 2 deletions src/Cli/dotnet/DotNetCommandFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ namespace Microsoft.DotNet.Cli
public class DotNetCommandFactory : ICommandFactory
{
private bool _alwaysRunOutOfProc;
private readonly string _currentWorkingDirectory;

public DotNetCommandFactory(bool alwaysRunOutOfProc = false)
public DotNetCommandFactory(bool alwaysRunOutOfProc = false, string currentWorkingDirectory = null)
{
_alwaysRunOutOfProc = alwaysRunOutOfProc;
_currentWorkingDirectory = currentWorkingDirectory;
}

public ICommand Create(
Expand All @@ -32,7 +34,7 @@ public ICommand Create(
return new BuiltInCommand(commandName, args, builtInCommand);
}

return CommandFactoryUsingResolver.CreateDotNet(commandName, args, framework, configuration);
return CommandFactoryUsingResolver.CreateDotNet(commandName, args, framework, configuration, _currentWorkingDirectory);
}

private bool TryGetBuiltInCommand(string commandName, out Func<string[], int> commandFunc)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ internal bool IsFirstParty(FilePath nupkgToVerify)
}
}

private static bool NuGetVerify(FilePath nupkgToVerify, out string commandOutput)
public static bool NuGetVerify(FilePath nupkgToVerify, out string commandOutput, string currentWorkingDirectory = null)
{
var args = new[] { "verify", "--all", nupkgToVerify.Value };
var command = new DotNetCommandFactory(alwaysRunOutOfProc: true)
var command = new DotNetCommandFactory(alwaysRunOutOfProc: true, currentWorkingDirectory)
.Create("nuget", args);

var commandResult = command.CaptureStdOut().Execute();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,18 @@
<data name="NuGetPackageSignatureVerificationSkipped" xml:space="preserve">
<value>Skipping NuGet package signature verification.</value>
</data>
<data name="VerifyingNuGetPackageSignature" xml:space="preserve">
<value>Verified that the NuGet package "{0}" has a valid signature.</value>
</data>
<data name="NuGetPackageShouldNotBeSigned" xml:space="preserve">
<value>Skipping signature verification for NuGet package "{0}" because it comes from a source that does not require signature validation.</value>
</data>
<data name="SkipNuGetpackageSigningValidationmacOSLinux" xml:space="preserve">
<value>Skip NuGet package signing validation. NuGet signing validation is not available on Linux or macOS https://aka.ms/workloadskippackagevalidation .</value>
</data>
<data name="FailedToValidatePackageSigning" xml:space="preserve">
<value>Failed to validate package signing.</value>
<value>Failed to validate package signing.
{0}</value>
</data>
<data name="FailedToFindSourceUnderPackageSourceMapping" xml:space="preserve">
<value>Package Source Mapping is enabled, but no source found under the specified package ID: {0}. See the documentation for Package Source Mapping at https://aka.ms/nuget-package-source-mapping for more details.</value>
Expand Down
53 changes: 33 additions & 20 deletions src/Cli/dotnet/NugetPackageDownloader/NuGetPackageDownloader.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.ToolPackage;
using Microsoft.DotNet.Tools;
using Microsoft.Extensions.EnvironmentAbstractions;
using Microsoft.TemplateEngine.Abstractions;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Credentials;
Expand Down Expand Up @@ -43,6 +40,7 @@ internal class NuGetPackageDownloader : INuGetPackageDownloader

private bool _verifySignatures;
private VerbosityOptions _verbosityOptions;
private readonly string _currentWorkingDirectory;

public NuGetPackageDownloader(
DirectoryPath packageInstallDir,
Expand All @@ -54,8 +52,10 @@ public NuGetPackageDownloader(
Func<IEnumerable<Task>> timer = null,
bool verifySignatures = false,
bool shouldUsePackageSourceMapping = false,
VerbosityOptions verbosityOptions = VerbosityOptions.normal)
VerbosityOptions verbosityOptions = VerbosityOptions.normal,
string currentWorkingDirectory = null)
{
_currentWorkingDirectory = currentWorkingDirectory;
_packageInstallDir = packageInstallDir;
_reporter = reporter ?? Reporter.Output;
_verboseLogger = verboseLogger ?? new NuGetConsoleLogger();
Expand Down Expand Up @@ -130,22 +130,22 @@ public async Task<string> DownloadPackageAsync(PackageId packageId,
packageVersion.ToNormalizedString()));
}

VerifySigning(nupkgPath);

await VerifySigning(nupkgPath, repository);
return nupkgPath;
}

private bool verbosityGreaterThanMinimal()
{
return _verbosityOptions != VerbosityOptions.quiet && _verbosityOptions != VerbosityOptions.q
&& _verbosityOptions != VerbosityOptions.minimal && _verbosityOptions != VerbosityOptions.m;
}
private bool VerbosityGreaterThanMinimal() =>
_verbosityOptions != VerbosityOptions.quiet && _verbosityOptions != VerbosityOptions.q &&
_verbosityOptions != VerbosityOptions.minimal && _verbosityOptions != VerbosityOptions.m;

private void VerifySigning(string nupkgPath)
private bool DiagnosticVerbosity() => _verbosityOptions == VerbosityOptions.diag || _verbosityOptions == VerbosityOptions.diagnostic;

private async Task VerifySigning(string nupkgPath, SourceRepository repository)
{
if (!_verifySignatures && !_validationMessagesDisplayed)
{
if (verbosityGreaterThanMinimal())
if (VerbosityGreaterThanMinimal())
{
_reporter.WriteLine(LocalizableStrings.NuGetPackageSignatureVerificationSkipped);
}
Expand All @@ -157,15 +157,28 @@ private void VerifySigning(string nupkgPath)
return;
}

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
if (repository is not null &&
await repository.GetResourceAsync<RepositorySignatureResource>().ConfigureAwait(false) is RepositorySignatureResource resource &&
resource.AllRepositorySigned)
{
if (!_firstPartyNuGetPackageSigningVerifier.Verify(new FilePath(nupkgPath),
out string commandOutput))
string commandOutput;
// The difference between _firstPartyNuGetPackageSigningVerifier.Verify and FirstPartyNuGetPackageSigningVerifier.NuGetVerify is that while NuGetVerify
// just ensures that the package is signed properly, Verify additionally requires that the package be from Microsoft. NuGetVerify does not require that
// the package be from Microsoft.
if ((!_shouldUsePackageSourceMapping && !_firstPartyNuGetPackageSigningVerifier.Verify(new FilePath(nupkgPath), out commandOutput)) ||
(_shouldUsePackageSourceMapping && !FirstPartyNuGetPackageSigningVerifier.NuGetVerify(new FilePath(nupkgPath), out commandOutput, _currentWorkingDirectory)))
{
throw new NuGetPackageInstallerException(LocalizableStrings.FailedToValidatePackageSigning +
Environment.NewLine +
commandOutput);
throw new NuGetPackageInstallerException(string.Format(LocalizableStrings.FailedToValidatePackageSigning, commandOutput));
}

if (DiagnosticVerbosity())
{
_reporter.WriteLine(LocalizableStrings.VerifyingNuGetPackageSignature, Path.GetFileNameWithoutExtension(nupkgPath));
}
}
else if (DiagnosticVerbosity())
{
_reporter.WriteLine(LocalizableStrings.NuGetPackageShouldNotBeSigned, Path.GetFileNameWithoutExtension(nupkgPath));
}
}

Expand Down Expand Up @@ -308,7 +321,7 @@ private static bool PackageIsInAllowList(IEnumerable<string> files)
private IEnumerable<PackageSource> LoadNuGetSources(PackageId packageId, PackageSourceLocation packageSourceLocation = null, PackageSourceMapping packageSourceMapping = null)
{
List<PackageSource> defaultSources = new List<PackageSource>();
string currentDirectory = Directory.GetCurrentDirectory();
string currentDirectory = _currentWorkingDirectory ?? Directory.GetCurrentDirectory();
ISettings settings;
if (packageSourceLocation?.NugetConfig != null)
{
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit f7ddf14

Please sign in to comment.