Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to download/export certificates from Trusted Signing #734

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/Sign.Cli/CodeCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ internal sealed class CodeCommand : Command
internal Option<HashAlgorithmName> TimestampDigestOption { get; } = new(["--timestamp-digest", "-td"], HashAlgorithmParser.ParseHashAlgorithmName, description: Resources.TimestampDigestOptionDescription);
internal Option<Uri?> TimestampUrlOption { get; } = new(["--timestamp-url", "-t"], ParseUrl, description: Resources.TimestampUrlOptionDescription);
internal Option<LogLevel> VerbosityOption { get; } = new(["--verbosity", "-v"], () => LogLevel.Warning, Resources.VerbosityOptionDescription);
internal Option<string> CertificateExportOption { get; } = new(["--certificate-export-path", "-co"], Resources.CertificateExportOptionDescription);

internal CodeCommand()
: base("code", Resources.CodeCommandDescription)
Expand All @@ -56,9 +57,11 @@ internal CodeCommand()
AddGlobalOption(TimestampDigestOption);
AddGlobalOption(MaxConcurrencyOption);
AddGlobalOption(VerbosityOption);
AddGlobalOption(CertificateExportOption);
}

internal async Task HandleAsync(InvocationContext context, IServiceProviderFactory serviceProviderFactory, ISignatureProvider signatureProvider, string fileArgument)
internal async Task HandleAsync(InvocationContext context, IServiceProviderFactory serviceProviderFactory,
ISignatureProvider signatureProvider, string fileArgument)
{
// Some of the options have a default value and that is why we can safely use
// the null-forgiving operator (!) to simplify the code.
Expand All @@ -74,6 +77,7 @@ internal async Task HandleAsync(InvocationContext context, IServiceProviderFacto
LogLevel verbosity = context.ParseResult.GetValueForOption(VerbosityOption);
string? output = context.ParseResult.GetValueForOption(OutputOption);
int maxConcurrency = context.ParseResult.GetValueForOption(MaxConcurrencyOption);
string? certificateExportPath = context.ParseResult.GetValueForOption(CertificateExportOption);

// Make sure this is rooted
if (!Path.IsPathRooted(baseDirectory.FullName))
Expand Down Expand Up @@ -184,7 +188,8 @@ internal async Task HandleAsync(InvocationContext context, IServiceProviderFacto
timestampUrl,
maxConcurrency,
fileHashAlgorithmName,
timestampHashAlgorithmName);
timestampHashAlgorithmName,
certificateExportPath);
}

private static string ExpandFilePath(DirectoryInfo baseDirectory, string file)
Expand Down
11 changes: 10 additions & 1 deletion src/Sign.Cli/Resources.Designer.cs

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

5 changes: 4 additions & 1 deletion src/Sign.Cli/Resources.resx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Expand Down Expand Up @@ -123,6 +123,9 @@
<data name="BaseDirectoryOptionDescription" xml:space="preserve">
<value>Base directory for files. Overrides the current working directory.</value>
</data>
<data name="CertificateExportOptionDescription" xml:space="preserve">
<value>Path to export certificate.</value>
</data>
<data name="CertificateStoreCommandDescription" xml:space="preserve">
<value>Use Windows Certificate Store or a local certificate file.</value>
</data>
Expand Down
72 changes: 72 additions & 0 deletions src/Sign.Core/Exporter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE.txt file in the project root for more information.

using System.Diagnostics;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Sign.Core;

internal class Exporter : IExporter
{
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<IExporter> _logger;

// Dependency injection requires a public constructor.
public Exporter(IServiceProvider serviceProvider, ILogger<IExporter> logger)
{
ArgumentNullException.ThrowIfNull(serviceProvider, nameof(serviceProvider));
ArgumentNullException.ThrowIfNull(logger, nameof(logger));

_serviceProvider = serviceProvider;
_logger = logger;
}

public async Task<int> ExportAsync(string outputPath)
{
try
{
ICertificateProvider certificateProvider = _serviceProvider.GetRequiredService<ICertificateProvider>();
using (X509Certificate2 certificate = await certificateProvider.GetCertificateAsync())
{
_logger.LogInformation(Resources.FetchedCertificateFingerprint, certificate.Thumbprint);

// Write out copy of public part of certificate if an output path was given
if (!string.IsNullOrWhiteSpace(outputPath))
{
// Ensure parent directory exists
string? parentDir = Path.GetDirectoryName(outputPath);
if (parentDir is not null && !Directory.Exists(parentDir))
{
_logger.LogDebug(Resources.CreatingDirectory, parentDir);
Directory.CreateDirectory(parentDir);
}

// Clean up any existing file
if (File.Exists(outputPath))
{
_logger.LogDebug(Resources.DeletingFile, outputPath);
File.Delete(outputPath);
_logger.LogDebug(Resources.DeletedFile, outputPath);
}

_logger.LogInformation(Resources.ExportingCertificate, outputPath);

var sw = Stopwatch.StartNew();
byte[] data = certificate.Export(X509ContentType.Cert);
await File.WriteAllBytesAsync(outputPath, data);
_logger.LogInformation(Resources.ExportSucceededWithTimeElapsed, sw.ElapsedMilliseconds);
}
}
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
return ExitCode.Failed;
}

return ExitCode.Success;
}
}
10 changes: 10 additions & 0 deletions src/Sign.Core/IExporter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE.txt file in the project root for more information.

namespace Sign.Core;

internal interface IExporter
{
Task<int> ExportAsync(string outputPath);
}
5 changes: 3 additions & 2 deletions src/Sign.Core/ISigner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Task<int> SignAsync(
Uri timestampUrl,
int maxConcurrency,
HashAlgorithmName fileHashAlgorithm,
HashAlgorithmName timestampHashAlgorithm);
HashAlgorithmName timestampHashAlgorithm,
string? certificateExportPath);
}
}
}
45 changes: 45 additions & 0 deletions src/Sign.Core/Resources.Designer.cs

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

22 changes: 21 additions & 1 deletion src/Sign.Core/Resources.resx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Expand Down Expand Up @@ -168,6 +168,14 @@
<value>Deleting directory {path}.</value>
<comment>{Placeholder="{path}"} is a directory path.</comment>
</data>
<data name="DeletedFile" xml:space="preserve">
<value>File {path} deleted.</value>
<comment>{Placeholder="{path}"} is a file path.</comment>
</data>
<data name="DeletingFile" xml:space="preserve">
<value>Deleting file {path}.</value>
<comment>{Placeholder="{path}"} is a file path.</comment>
</data>
<data name="DirectoryNotDeleted" xml:space="preserve">
<value>Directory {path} still exists.</value>
<comment>{Placeholder="{path}"} is a directory path.</comment>
Expand All @@ -183,10 +191,22 @@
<value>An exception occurred while attempting to delete directory {path}.</value>
<comment>{Placeholder="{path}"} is a directory path.</comment>
</data>
<data name="ExportingCertificate" xml:space="preserve">
<value>Exporting certificate to {path}.</value>
<comment>{Placeholder="{path}"} is a path to a certificate file.</comment>
</data>
<data name="ExportSucceededWithTimeElapsed" xml:space="preserve">
<value>Completed in {millseconds} ms.</value>
<comment>{Placeholder="{milliseconds}"} is a decimal number representing the number of milliseconds elapsed, and "ms" is the unit abbreviation for milliseconds.</comment>
</data>
<data name="FetchedCertificate" xml:space="preserve">
<value>Fetched certificate. [{milliseconds} ms]</value>
<comment>{Placeholder="{milliseconds}"} is a decimal number representing the number of milliseconds elapsed, and "ms" is the unit abbreviation for milliseconds.</comment>
</data>
<data name="FetchedCertificateFingerprint" xml:space="preserve">
<value>Fetched certificate with fingerprint {fingerprint}.</value>
<comment>{Placeholder="{fingerprint}"} is an identifier for a certificate.</comment>
</data>
<data name="FetchingCertificate" xml:space="preserve">
<value>Fetching certificate from Azure Key Vault.</value>
</data>
Expand Down
3 changes: 2 additions & 1 deletion src/Sign.Core/ServiceProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ internal static ServiceProvider CreateDefault(
services.AddSingleton<IVsixSignTool, VsixSignTool>();
services.AddSingleton<ICertificateVerifier, CertificateVerifier>();
services.AddSingleton<ISigner, Signer>();
services.AddSingleton<IExporter, Exporter>();

if (addServices is not null)
{
Expand All @@ -85,4 +86,4 @@ internal static ServiceProvider CreateDefault(
return new ServiceProvider(services.BuildServiceProvider());
}
}
}
}
13 changes: 11 additions & 2 deletions src/Sign.Core/Signer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ public async Task<int> SignAsync(
Uri timestampUrl,
int maxConcurrency,
HashAlgorithmName fileHashAlgorithm,
HashAlgorithmName timestampHashAlgorithm)
HashAlgorithmName timestampHashAlgorithm,
string? certificateExportPath)
{
IAggregatingDataFormatSigner signer = _serviceProvider.GetRequiredService<IAggregatingDataFormatSigner>();
IDirectoryService directoryService = _serviceProvider.GetRequiredService<IDirectoryService>();
Expand Down Expand Up @@ -76,6 +77,14 @@ public async Task<int> SignAsync(
{
using (X509Certificate2 certificate = await certificateProvider.GetCertificateAsync())
{
if (!string.IsNullOrWhiteSpace(certificateExportPath))
{
string fullExportPath = ExpandFilePath(baseDirectory, certificateExportPath);

IExporter exporter = _serviceProvider.GetRequiredService<IExporter>();
await exporter.ExportAsync(fullExportPath);
}

ICertificateVerifier certificateVerifier = _serviceProvider.GetRequiredService<ICertificateVerifier>();

certificateVerifier.Verify(certificate);
Expand Down Expand Up @@ -186,4 +195,4 @@ private static string ExpandFilePath(DirectoryInfo baseDirectory, string file)
return file;
}
}
}
}
7 changes: 5 additions & 2 deletions test/Sign.Cli.Test/TestInfrastructure/SignerSpy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ internal sealed class SignerSpy : ISigner
internal int? MaxConcurrency { get; private set; }
internal HashAlgorithmName? FileHashAlgorithm { get; private set; }
internal HashAlgorithmName? TimestampHashAlgorithm { get; private set; }
internal string? CertificateExportPath { get; private set; }
internal int ExitCode { get; }

internal SignerSpy()
Expand All @@ -40,7 +41,8 @@ public Task<int> SignAsync(
Uri timestampUrl,
int maxConcurrency,
HashAlgorithmName fileHashAlgorithm,
HashAlgorithmName timestampHashAlgorithm)
HashAlgorithmName timestampHashAlgorithm,
string? certificateExportPath)
{
InputFiles = inputFiles;
OutputFile = outputFile;
Expand All @@ -54,8 +56,9 @@ public Task<int> SignAsync(
MaxConcurrency = maxConcurrency;
FileHashAlgorithm = fileHashAlgorithm;
TimestampHashAlgorithm = timestampHashAlgorithm;
CertificateExportPath = certificateExportPath;

return Task.FromResult(ExitCode);
}
}
}
}
5 changes: 3 additions & 2 deletions test/Sign.Core.Test/SignerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,8 @@ private async Task SignAsync(TemporaryDirectory temporaryDirectory, IReadOnlyLis
_certificatesFixture.TimestampServiceUrl,
maxConcurrency: 4,
HashAlgorithmName.SHA256,
HashAlgorithmName.SHA256);
HashAlgorithmName.SHA256,
null);

Assert.Equal(ExitCode.Success, exitCode);

Expand Down Expand Up @@ -624,4 +625,4 @@ private static void RegisterSipsFromIniFile()
Kernel32.LoadLibraryW($@"{baseDirectory}\mssign32.dll");
}
}
}
}