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

Test of https://github.com/dotnet/arcade/pull/15216 #15223

Closed
wants to merge 5 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
5 changes: 5 additions & 0 deletions src/Microsoft.DotNet.Arcade.Sdk/tools/Sign.props
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@
a public key token.
The certificate can be overriden using the StrongNameSignInfo or the FileSignInfo item group.
-->
<!--
Collision priority ID needed to avoid failures with duplicate FileExtensionSignInfo for ".deb".
See https://github.com/dotnet/arcade/pull/15216#discussion_r1828513419
-->
<FileExtensionSignInfo Include=".deb" CertificateName="LinuxSign" CollisionPriorityId="0" />
<FileExtensionSignInfo Include=".jar" CertificateName="MicrosoftJARSHA2" />
<FileExtensionSignInfo Include=".js;.ps1;.psd1;.psm1;.psc1;.py" CertificateName="Microsoft400" />
<FileExtensionSignInfo Include=".dll;.exe;.mibc" CertificateName="Microsoft400" />
Expand Down
5 changes: 5 additions & 0 deletions src/Microsoft.DotNet.SignTool.Tests/FakeSignTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ private static void SignPEFile(string path)
}
}

public override bool VerifySignedDeb(TaskLoggingHelper log, string filePath)
{
return true;
}

public override bool VerifySignedPowerShellFile(string filePath)
{
return true;
Expand Down
Binary file not shown.
51 changes: 48 additions & 3 deletions src/Microsoft.DotNet.SignTool.Tests/SignToolTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public class SignToolTests : IDisposable
{".psm1", new List<SignInfo>{ new SignInfo("PSMCertificate") } },
{".psc1", new List<SignInfo>{ new SignInfo("PSCCertificate") } },
{".dylib", new List<SignInfo>{ new SignInfo("DylibCertificate") } },
{".deb", new List<SignInfo>{ new SignInfo("LinuxSign") } },
{".dll", new List<SignInfo>{ new SignInfo("Microsoft400") } }, // lgtm [cs/common-default-passwords] Safe, these are certificate names
{".exe", new List<SignInfo>{ new SignInfo("Microsoft400") } }, // lgtm [cs/common-default-passwords] Safe, these are certificate names
{".msi", new List<SignInfo>{ new SignInfo("Microsoft400") } }, // lgtm [cs/common-default-passwords] Safe, these are certificate names
Expand All @@ -51,6 +52,7 @@ public class SignToolTests : IDisposable
{ ".psm1", new List<SignInfo>{ new SignInfo("PSMCertificate", collisionPriorityId: "123") } },
{ ".psc1", new List<SignInfo>{ new SignInfo("PSCCertificate", collisionPriorityId: "123") } },
{ ".dylib", new List<SignInfo>{ new SignInfo("DylibCertificate", collisionPriorityId: "123") } },
{ ".deb", new List<SignInfo>{ new SignInfo("LinuxSign", collisionPriorityId: "123") } },
{ ".dll", new List<SignInfo>
{
new SignInfo("Microsoft400", collisionPriorityId: "123"), // lgtm [cs/common-default-passwords] Safe, these are certificate names
Expand Down Expand Up @@ -97,6 +99,10 @@ public class SignToolTests : IDisposable
{ "CertificateName", "DylibCertificate" },
{ SignToolConstants.CollisionPriorityId, "123" }
}),
new TaskItem(".deb", new Dictionary<string, string> {
{ "CertificateName", "LinuxSign" },
{ SignToolConstants.CollisionPriorityId, "123" }
}),
new TaskItem(".dll", new Dictionary<string, string> {
{ "CertificateName", "Microsoft400" }, // lgtm [cs/common-default-passwords] Safe, these are certificate names
{ SignToolConstants.CollisionPriorityId, "123" }
Expand Down Expand Up @@ -231,7 +237,9 @@ public class SignToolTests : IDisposable
".esd",

".py",
".pyd"
".pyd",

".deb",
};

public static IEnumerable<object[]> GetSignableExtensions()
Expand Down Expand Up @@ -365,10 +373,17 @@ private void ValidateFileSignInfos(
var task = new SignToolTask { BuildEngine = engine };
var signingInput = new Configuration(_tmpDir, itemsToSign, strongNameSignInfo, fileSignInfo, extensionsSignInfo, dualCertificates, tarToolPath: s_tarToolPath, task.Log).GenerateListOfFiles();

signingInput.FilesToSign.Select(f => f.ToString()).Should().BeEquivalentTo(expected);
signingInput.FilesToCopy.Select(f => $"{f.Key} -> {f.Value}").Should().BeEquivalentTo(expectedCopyFiles ?? Array.Empty<string>());
engine.LogErrorEvents.Select(w => w.Message).Should().BeEquivalentTo(expectedErrors ?? Array.Empty<string>());
engine.LogWarningEvents.Select(w => $"{w.Code}: {w.Message}").Should().BeEquivalentTo(expectedWarnings ?? Array.Empty<string>());

// output log events for debugging
foreach (var logEvent in engine.LogMessageEvents)
{
_output.WriteLine(logEvent.Message);
}

signingInput.FilesToSign.Select(f => f.ToString()).Should().BeEquivalentTo(expected);
signingInput.FilesToCopy.Select(f => $"{f.Key} -> {f.Value}").Should().BeEquivalentTo(expectedCopyFiles ?? Array.Empty<string>());
}

[Fact]
Expand Down Expand Up @@ -1206,6 +1221,36 @@ public void SignedSymbolsNupkg()
});
}

[Fact]
public void CheckDebSigning()
{
// List of files to be considered for signing
var itemsToSign = new ITaskItem[]
{
new TaskItem(GetResourcePath("test.deb"))
};

// Default signing information
var strongNameSignInfo = new Dictionary<string, List<SignInfo>>();

// Overriding information
var fileSignInfo = new Dictionary<ExplicitCertificateKey, string>();

ValidateFileSignInfos(itemsToSign, strongNameSignInfo, fileSignInfo, s_fileExtensionSignInfo, new[]
{
"File 'test.deb' Certificate='LinuxSign'"
});

ValidateGeneratedProject(itemsToSign, strongNameSignInfo, fileSignInfo, s_fileExtensionSignInfo, new[]
{
$@"
<FilesToSign Include=""{Uri.EscapeDataString(Path.Combine(_tmpDir, "test.deb"))}"">
<Authenticode>LinuxSign</Authenticode>
</FilesToSign>
"
});
}

[Fact]
public void CheckPowershellSigning()
{
Expand Down
31 changes: 28 additions & 3 deletions src/Microsoft.DotNet.SignTool/src/BatchSignUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using TaskLoggingHelper = Microsoft.Build.Utilities.TaskLoggingHelper;

Expand Down Expand Up @@ -84,7 +85,7 @@ internal void Go(bool doStrongNameCheck)
// This is a recursive process since we process nested containers.
foreach (var file in _batchData.FilesToSign)
{
VerifyAfterSign(file);
VerifyAfterSign(_log, file);
}

if (_log.HasLoggedErrors)
Expand Down Expand Up @@ -495,6 +496,17 @@ private void VerifyCertificates(TaskLoggingHelper log)
log.LogError($"VSIX {fileName} cannot be strong name signed.");
}
}
else if (fileName.IsDeb())
{
if (isInvalidEmptyCertificate)
{
log.LogError($"Deb package {fileName} should have a certificate name.");
}
if (!IsLinuxSignCertificate(fileName.SignInfo.Certificate))
{
log.LogError($"Deb package {fileName} must be signed with a LinuxSign certificate.");
}
}
else if (fileName.IsNupkg())
{
if(isInvalidEmptyCertificate)
Expand Down Expand Up @@ -534,7 +546,7 @@ private void VerifyCertificates(TaskLoggingHelper log)
}
}

private void VerifyAfterSign(FileSignInfo file)
private void VerifyAfterSign(TaskLoggingHelper log, FileSignInfo file)
{
if (file.IsPEFile())
{
Expand All @@ -550,6 +562,17 @@ private void VerifyAfterSign(FileSignInfo file)
}
}
}
else if (file.IsDeb())
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_log.LogMessage(MessageImportance.Low, $"Skipping signature verification of {file.FullPath} on Windows.");
}
else if (!_signTool.VerifySignedDeb(log, file.FullPath))
{
_log.LogError($"Deb package {file.FullPath} is not signed properly.");
}
}
else if (file.IsPowerShellScript())
{
if (!_signTool.VerifySignedPowerShellFile(file.FullPath))
Expand Down Expand Up @@ -582,7 +605,7 @@ private void VerifyAfterSign(FileSignInfo file)
continue;
}

VerifyAfterSign(zipPart.Value.FileSignInfo);
VerifyAfterSign(_log, zipPart.Value.FileSignInfo);
}

if (!SkipZipContainerSignatureMarkerCheck)
Expand Down Expand Up @@ -621,5 +644,7 @@ private void VerifyStrongNameSigning()
}

private static bool IsVsixCertificate(string certificate) => certificate.StartsWith("Vsix", StringComparison.OrdinalIgnoreCase);

private static bool IsLinuxSignCertificate(string certificate) => certificate.StartsWith("LinuxSign", StringComparison.OrdinalIgnoreCase);
}
}
12 changes: 12 additions & 0 deletions src/Microsoft.DotNet.SignTool/src/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,18 @@ private FileSignInfo ExtractSignInfo(
_log.LogMessage(MessageImportance.Low, $"File {file.FullPath} is digitally signed.");
}
}
else if(FileSignInfo.IsDeb(file.FullPath))
{
isAlreadySigned = VerifySignatures.VerifySignedDeb(_log, file.FullPath);
if (!isAlreadySigned)
{
_log.LogMessage(MessageImportance.Low, $"File {file.FullPath} is not signed.");
}
else
{
_log.LogMessage(MessageImportance.Low, $"File {file.FullPath} is signed.");
}
}
else if(FileSignInfo.IsPowerShellScript(file.FullPath))
{
isAlreadySigned = VerifySignatures.VerifySignedPowerShellFile(file.FullPath);
Expand Down
5 changes: 5 additions & 0 deletions src/Microsoft.DotNet.SignTool/src/FileSignInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ internal readonly struct FileSignInfo
// optional file information that allows to disambiguate among multiple files with the same name:
internal readonly string TargetFramework;

internal static bool IsDeb(string path)
=> Path.GetExtension(path) == ".deb";

internal static bool IsPEFile(string path)
=> Path.GetExtension(path) == ".exe" || Path.GetExtension(path) == ".dll";

Expand Down Expand Up @@ -59,6 +62,8 @@ internal static bool IsPackage(string path)
internal static bool IsZipContainer(string path)
=> IsPackage(path) || IsMPack(path) || IsZip(path) || IsTarGZip(path);

internal bool IsDeb() => IsDeb(FileName);

internal bool IsPEFile() => IsPEFile(FileName);

internal bool IsManaged() => ContentUtil.IsManaged(FullPath);
Expand Down
5 changes: 5 additions & 0 deletions src/Microsoft.DotNet.SignTool/src/RealSignTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@ public override bool VerifyStrongNameSign(string fileFullPath)
return process.ExitCode == 0;
}

public override bool VerifySignedDeb(TaskLoggingHelper log, string filePath)
{
return VerifySignatures.VerifySignedDeb(log, filePath);
}

public override bool VerifySignedPowerShellFile(string filePath)
{
return VerifySignatures.VerifySignedPowerShellFile(filePath);
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.DotNet.SignTool/src/SignTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ internal SignTool(SignToolArgs args, TaskLoggingHelper log)

public abstract bool LocalStrongNameSign(IBuildEngine buildEngine, int round, IEnumerable<FileSignInfo> files);

public abstract bool VerifySignedDeb(TaskLoggingHelper log, string filePath);
public abstract bool VerifySignedPEFile(Stream stream);
public abstract bool VerifySignedPowerShellFile(string filePath);
public abstract bool VerifySignedNugetFileMarker(string filePath);
Expand Down
5 changes: 4 additions & 1 deletion src/Microsoft.DotNet.SignTool/src/SignToolConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ internal static class SignToolConstants
public const string MsiEngineExtension = "-engine.exe";
/// <summary>
/// List of known signable extensions. Copied, removing duplicates, from here:
/// https://microsoft.sharepoint.com/teams/codesigninfo/Wiki/Signable%20Files.aspx
/// https://microsoft.sharepoint.com/teams/prss/Codesign/SitePages/Signable%20Files.aspx
/// ".deb" is not in the list linked above, but it is a known signable extension.
/// </summary>
public static readonly HashSet<string> SignableExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
Expand Down Expand Up @@ -110,6 +111,8 @@ internal static class SignToolConstants

".py",
".pyd",

".deb",
};

/// <summary>
Expand Down
3 changes: 3 additions & 0 deletions src/Microsoft.DotNet.SignTool/src/ValidationOnlySignTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ public override void RemovePublicSign(string assemblyPath)
{
}

public override bool VerifySignedDeb(TaskLoggingHelper log, string filePath)
=> true;

public override bool VerifySignedPEFile(Stream assemblyStream)
=> true;

Expand Down
77 changes: 77 additions & 0 deletions src/Microsoft.DotNet.SignTool/src/VerifySignatures.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NuGet.Common;
using NuGet.Packaging;
using NuGet.Packaging.Signing;
using System;
using System.IO;
using System.IO.Compression;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
Expand All @@ -16,6 +21,55 @@ namespace Microsoft.DotNet.SignTool
{
internal class VerifySignatures
{
internal static bool VerifySignedDeb(TaskLoggingHelper log, string filePath)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// We cannot check the signature of a .deb file on Windows.
log.LogMessage(MessageImportance.Low, $"Skipping signature verification of {filePath} on Windows.");
return false;
}

string tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempDir);

// https://microsoft.sharepoint.com/teams/prss/esrp/info/SitePages/Linux%20GPG%20Signing.aspx
try
{
// Download the Microsoft public key
using (HttpClient client = new HttpClient())
{
using (Stream stream = client.GetStreamAsync("https://packages.microsoft.com/keys/microsoft.asc").Result)
{
using (FileStream fileStream = File.Create($"{tempDir}/microsoft.asc"))
{
stream.CopyTo(fileStream);
}
}
}

RunCommand($"ar x {filePath} --output {tempDir}");
RunCommand($"gpg --import {tempDir}/microsoft.asc");
RunCommand($"cat {tempDir}/debian-binary {tempDir}/control.tar.gz {tempDir}/data.tar.gz > {tempDir}/combined-contents");
string output = RunCommand($"gpg --verify {tempDir}/_gpgorigin {tempDir}/combined-contents");
if (output.Contains("Good signature"))
{
return true;
}

return false;
}
catch(Exception e)
{
log.LogMessage(MessageImportance.Low, $"Failed to verify signature of {filePath} with the following error: {e.Message}");
return false;
}
finally
{
Directory.Delete(tempDir, true);
}
}

internal static bool VerifySignedPowerShellFile(string filePath)
{
return File.ReadLines(filePath).Any(line => line.IndexOf("# SIG # Begin Signature Block", StringComparison.OrdinalIgnoreCase) >= 0);
Expand Down Expand Up @@ -121,5 +175,28 @@ internal static bool IsDigitallySigned(string fullPath)
}
return certificate.Verify();
}

private static string RunCommand(string command)
{
var psi = new ProcessStartInfo
{
FileName = "bash",
Arguments = $"-c \"{command}\"",
RedirectStandardOutput = true,
RedirectStandardError = false,
UseShellExecute = false,
CreateNoWindow = true
};

using (var process = Process.Start(psi))
{
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception($"Command '{command}' failed with exit code {process.ExitCode}");
}
return process.StandardOutput.ReadToEnd();
}
}
}
}
Loading