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 managed MachO signing #108992

Merged
merged 35 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
8901e5e
Add managed MachO signing
jtschuster Oct 17, 2024
10fc3b3
Add managed MachO signing
jtschuster Oct 17, 2024
f2f8402
Merge branch 'MachSigning' of https://github.com/jtschuster/runtime i…
jtschuster Oct 17, 2024
65a5a46
PR feedback, use different memory map file workaround
jtschuster Oct 18, 2024
c4425e9
Set enableMacOSCodesign=true in singlefile test
jtschuster Oct 19, 2024
622b32c
Make NameBuffer constants more readable
jtschuster Oct 21, 2024
b69eafd
Update src/installer/managed/Microsoft.NET.HostModel/MachO/MachMagicE…
jtschuster Oct 21, 2024
ed70909
Update src/installer/managed/Microsoft.NET.HostModel/MachO/MachMagicE…
jtschuster Oct 21, 2024
72e2ccf
PR Feedback:
jtschuster Oct 22, 2024
f92c9fa
Handle folders in the test data package
jtschuster Oct 22, 2024
6784db8
PR feedback
jtschuster Oct 24, 2024
4be00c2
Merge branch 'main' of https://github.com/dotnet/runtime into MachSig…
jtschuster Oct 24, 2024
9c6b1bc
Fix test issues
jtschuster Oct 25, 2024
5d8fe8e
Merge branch 'main' of https://github.com/dotnet/runtime into MachSig…
jtschuster Oct 25, 2024
3a2351b
Move BinaryFormat files and Enums to separate folders and add notes a…
jtschuster Oct 28, 2024
5eafdcb
Extend the AppHost template on disk before modifying and signing. Rem…
jtschuster Oct 28, 2024
f58574e
Use new MachO types in MachOUtils.cs
jtschuster Oct 28, 2024
b551128
Fix comments, use explicit types, update darc dependencies
jtschuster Oct 28, 2024
58f5144
Use unsafe and sizeof instead of Marshal.SizeOf, fix format nits
jtschuster Oct 29, 2024
4b77556
Rename signatureLC to signatureLoadCommand, remove unnecessary methods
jtschuster Oct 29, 2024
4a1f133
Remove extra 'unsafe' blocks
jtschuster Oct 29, 2024
78605a0
Revert arguments string change
jtschuster Oct 29, 2024
272f0e5
Re-add ResourceUpdater to HostWriter
jtschuster Oct 29, 2024
4a46cb9
Move CodeSignature to a nested type within MachObjectFile, move signa…
jtschuster Oct 29, 2024
e81000a
Merge branch 'main' of https://github.com/dotnet/runtime into MachSig…
jtschuster Oct 29, 2024
3cdc7ce
Set file length after memory mapped file is disposed
jtschuster Oct 29, 2024
a18cb1b
Close memory mapped file in test signing method.
jtschuster Oct 30, 2024
5320d1f
PR Feedback
jtschuster Oct 31, 2024
71cadf4
Merge branch 'main' of https://github.com/dotnet/runtime into MachSig…
jtschuster Oct 31, 2024
2a36163
Revert local testing change that enabled codesigning always.
jtschuster Oct 31, 2024
980c755
Revert extra change in TestApp.cs
jtschuster Oct 31, 2024
2cf8e41
Remove license from ThirdPartyNotices
jtschuster Oct 31, 2024
a8956b3
Add more definitions links, fix test nits.
jtschuster Nov 11, 2024
0c7e528
Merge branch 'main' of https://github.com/dotnet/runtime into MachSig…
jtschuster Nov 11, 2024
753c73c
Add comment explaining why the file must be written to create signatu…
jtschuster Nov 11, 2024
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
24 changes: 24 additions & 0 deletions THIRD-PARTY-NOTICES.TXT
Original file line number Diff line number Diff line change
Expand Up @@ -1394,3 +1394,27 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

License notice for Melanzana MachO signing
------------------------------------------
MIT License

Copyright (c) 2021 Filip Navara

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
54 changes: 32 additions & 22 deletions src/installer/managed/Microsoft.NET.HostModel/AppHost/HostWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.NET.HostModel.MachO;

namespace Microsoft.NET.HostModel.AppHost
{
Expand Down Expand Up @@ -60,7 +61,7 @@ public enum SearchLocation : byte
/// <param name="appBinaryFilePath">Full path to app binary or relative path to the result apphost file</param>
/// <param name="windowsGraphicalUserInterface">Specify whether to set the subsystem to GUI. Only valid for PE apphosts.</param>
/// <param name="assemblyToCopyResourcesFrom">Path to the intermediate assembly, used for copying resources to PE apphosts.</param>
/// <param name="enableMacOSCodeSign">Sign the app binary using codesign with an anonymous certificate.</param>
/// <param name="enableMacOSCodeSign">Sign the app binary with an anonymous certificate. Only use when the AppHost is a Mach-O file built for MacOS.</param>
/// <param name="disableCetCompat">Remove CET Shadow Stack compatibility flag if set</param>
/// <param name="dotNetSearchOptions">Options for how the created apphost should look for the .NET install</param>
public static void CreateAppHost(
Expand Down Expand Up @@ -112,6 +113,10 @@ void RewriteAppHost(MemoryMappedFile mappedFile, MemoryMappedViewAccessor access
{
PEUtils.RemoveCetCompatBit(mappedFile, accessor);
}
if (appHostIsPEImage && enableMacOSCodeSign)
jtschuster marked this conversation as resolved.
Show resolved Hide resolved
{
throw new InvalidDataException("Cannot sign a PE image with MacOS code signing.");
}
}

try
Expand All @@ -125,28 +130,42 @@ void RewriteAppHost(MemoryMappedFile mappedFile, MemoryMappedViewAccessor access
{
// Open the source host file.
appHostSourceStream = new FileStream(appHostSourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1);
memoryMappedFile = MemoryMappedFile.CreateFromFile(appHostSourceStream, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true);
memoryMappedViewAccessor = memoryMappedFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.CopyOnWrite);

// Get the size of the source app host to ensure that we don't write extra data to the destination.
// On Windows, the size of the view accessor is rounded up to the next page boundary.
jtschuster marked this conversation as resolved.
Show resolved Hide resolved
long sourceAppHostLength = appHostSourceStream.Length;
var appHostLength = appHostSourceStream.Length;
jtschuster marked this conversation as resolved.
Show resolved Hide resolved
memoryMappedFile = MemoryMappedFile.CreateFromFile(appHostSourceStream, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true);
memoryMappedViewAccessor = memoryMappedFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.CopyOnWrite);

// Transform the host file in-memory.
RewriteAppHost(memoryMappedFile, memoryMappedViewAccessor);

// Save the transformed host.
using (FileStream fileStream = new FileStream(appHostDestinationFilePath, FileMode.Create))
MachObjectFile machObjectFile = null;
if (!appHostIsPEImage)
{
BinaryUtils.WriteToStream(memoryMappedViewAccessor, fileStream, sourceAppHostLength);

// Remove the signature from MachO hosts.
if (!appHostIsPEImage)
if (enableMacOSCodeSign)
{
string fileName = Path.GetFileName(appHostDestinationFilePath);
machObjectFile = new MachObjectFile(memoryMappedViewAccessor, fileName);
appHostLength = machObjectFile.CreateAdHocSignature(memoryMappedViewAccessor, fileName);
}
else
{
MachOUtils.RemoveSignature(fileStream);
if (MachObjectFile.TryRemoveCodesign(memoryMappedViewAccessor, out long? length))
agocke marked this conversation as resolved.
Show resolved Hide resolved
{
appHostLength = length.Value;
}
}
}

if (assemblyToCopyResourcesFrom != null && appHostIsPEImage)
// Save the transformed host.
using (FileStream fileStream = new FileStream(appHostDestinationFilePath, FileMode.Create, FileAccess.ReadWrite))
elinor-fung marked this conversation as resolved.
Show resolved Hide resolved
{
BinaryUtils.WriteToStream(memoryMappedViewAccessor, fileStream, appHostLength);
if (!appHostIsPEImage && enableMacOSCodeSign)
{
machObjectFile.WriteCodeSignature(fileStream);
jtschuster marked this conversation as resolved.
Show resolved Hide resolved
}
if (appHostIsPEImage && assemblyToCopyResourcesFrom != null)
{
using var updater = new ResourceUpdater(fileStream, true);
updater.AddResourcesFromPEImage(assemblyToCopyResourcesFrom);
Expand Down Expand Up @@ -178,15 +197,6 @@ void RewriteAppHost(MemoryMappedFile mappedFile, MemoryMappedViewAccessor access
{
throw new Win32Exception(Marshal.GetLastWin32Error(), $"Could not set file permission {Convert.ToString(filePermissionOctal, 8)} for {appHostDestinationFilePath}.");
}

if (enableMacOSCodeSign && RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && HostModelUtils.IsCodesignAvailable())
{
(int exitCode, string stdErr) = HostModelUtils.RunCodesign("-s -", appHostDestinationFilePath);
if (exitCode != 0)
{
throw new AppHostSigningException(exitCode, stdErr);
}
}
}
}
catch (Exception ex)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Microsoft.NET.HostModel.Tests, PublicKey="
+ "00240000048000009400000006020000"
+ "00240000525341310004000001000100"
+ "b5fc90e7027f67871e773a8fde8938c8"
+ "1dd402ba65b9201d60593e96c492651e"
+ "889cc13f1415ebb53fac1131ae0bd333"
+ "c5ee6021672d9718ea31a8aebd0da007"
+ "2f25d87dba6fc90ffd598ed4da35e44c"
+ "398c454307e8e33b8426143daec9f596"
+ "836f97c8f74750e5975c64e2189f45de"
+ "f46b2a2b1247adc3652bf5c308055da9")]

[assembly: InternalsVisibleTo("Microsoft.NET.HostModel.MachO.Tests, PublicKey="
jtschuster marked this conversation as resolved.
Show resolved Hide resolved
+ "00240000048000009400000006020000"
+ "00240000525341310004000001000100"
+ "b5fc90e7027f67871e773a8fde8938c8"
+ "1dd402ba65b9201d60593e96c492651e"
+ "889cc13f1415ebb53fac1131ae0bd333"
+ "c5ee6021672d9718ea31a8aebd0da007"
+ "2f25d87dba6fc90ffd598ed4da35e44c"
+ "398c454307e8e33b8426143daec9f596"
+ "836f97c8f74750e5975c64e2189f45de"
+ "f46b2a2b1247adc3652bf5c308055da9")]
26 changes: 5 additions & 21 deletions src/installer/managed/Microsoft.NET.HostModel/Bundle/Bundler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using Microsoft.DotNet.CoreSetup;
using Microsoft.NET.HostModel.AppHost;

namespace Microsoft.NET.HostModel.Bundle
Expand Down Expand Up @@ -272,9 +273,9 @@ public string GenerateBundle(IReadOnlyList<FileSpec> fileSpecs)

BinaryUtils.CopyFile(hostSource, bundlePath);

if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && HostModelUtils.IsCodesignAvailable())
if (_target.IsOSX && RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && Codesign.IsAvailable)
{
RemoveCodesignIfNecessary(bundlePath);
Codesign.Run("--remove-signature", bundlePath);
}

// Note: We're comparing file paths both on the OS we're running on as well as on the target OS for the app
Expand Down Expand Up @@ -346,33 +347,16 @@ public string GenerateBundle(IReadOnlyList<FileSpec> fileSpecs)
HostWriter.SetAsBundle(bundlePath, headerOffset);

// Sign the bundle if requested
if (_macosCodesign && RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && HostModelUtils.IsCodesignAvailable())
if (_macosCodesign && RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && Codesign.IsAvailable)
{
var (exitCode, stdErr) = HostModelUtils.RunCodesign("-s -", bundlePath);
var (exitCode, stdErr) = Codesign.Run("-s -", bundlePath);
jtschuster marked this conversation as resolved.
Show resolved Hide resolved
if (exitCode != 0)
{
throw new InvalidOperationException($"Failed to codesign '{bundlePath}': {stdErr}");
}
}

return bundlePath;

// Remove mac code signature if applied before bundling
static void RemoveCodesignIfNecessary(string bundlePath)
{
Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.OSX));
Debug.Assert(HostModelUtils.IsCodesignAvailable());

// `codesign -v` returns 0 if app is signed
if (HostModelUtils.RunCodesign("-v", bundlePath).ExitCode == 0)
{
var (exitCode, stdErr) = HostModelUtils.RunCodesign("--remove-signature", bundlePath);
if (exitCode != 0)
{
throw new InvalidOperationException($"Removing codesign from '{bundlePath}' failed: {stdErr}");
}
}
}
}
}
}
38 changes: 38 additions & 0 deletions src/installer/managed/Microsoft.NET.HostModel/Bundle/Codesign.cs
jtschuster marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

namespace Microsoft.DotNet.CoreSetup
{
public class Codesign
{
private const string CodesignPath = @"/usr/bin/codesign";
jtschuster marked this conversation as resolved.
Show resolved Hide resolved

public static bool IsAvailable => File.Exists(CodesignPath);

public static (int ExitCode, string StdErr) Run(string args, string appHostPath)
{
Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.OSX));
Debug.Assert(IsAvailable);

var psi = new ProcessStartInfo()
{
Arguments = $"{args} \"{appHostPath}\"",
jtschuster marked this conversation as resolved.
Show resolved Hide resolved
FileName = CodesignPath,
RedirectStandardError = true,
UseShellExecute = false,
};

using (var p = Process.Start(psi))
{
if (p == null)
return (-1, "Failed to start process");
p.WaitForExit();
return (p.ExitCode, p.StandardError.ReadToEnd());
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.NET.HostModel.MachO;
using Microsoft.NET.HostModel.AppHost;
using System;
using System.Diagnostics;
Expand Down Expand Up @@ -77,7 +78,7 @@ public TargetInfo(OSPlatform? os, Architecture? arch, Version targetFrameworkVer

public bool IsNativeBinary(string filePath)
{
return IsWindows ? PEUtils.IsPEImage(filePath) : IsOSX ? MachOUtils.IsMachOImage(filePath) : ElfUtils.IsElfImage(filePath);
return IsWindows ? PEUtils.IsPEImage(filePath) : IsOSX ? AppHost.MachOUtils.IsMachOImage(filePath) : ElfUtils.IsElfImage(filePath);
jtschuster marked this conversation as resolved.
Show resolved Hide resolved
}

public string GetAssemblyName(string hostName)
Expand Down
22 changes: 22 additions & 0 deletions src/installer/managed/Microsoft.NET.HostModel/MachO/BlobIndex.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Runtime.InteropServices;

namespace Microsoft.NET.HostModel.MachO;

[StructLayout(LayoutKind.Sequential)]
internal struct BlobIndex
{
private readonly CodeDirectorySpecialSlot _slot;
private readonly uint _offset;

public CodeDirectorySpecialSlot Slot => (CodeDirectorySpecialSlot)((uint)_slot).ConvertFromBigEndian();
public uint Offset => _offset.ConvertFromBigEndian();

public BlobIndex(CodeDirectorySpecialSlot slot, uint offset)
{
_slot = (CodeDirectorySpecialSlot)((uint)slot).MakeBigEndian();
_offset = offset.MakeBigEndian();
}
}
12 changes: 12 additions & 0 deletions src/installer/managed/Microsoft.NET.HostModel/MachO/BlobMagic.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.NET.HostModel.MachO;

internal enum BlobMagic : uint
{
Requirements = 0xfade0c01,
CodeDirectory = 0xfade0c02,
EmbeddedSignature = 0xfade0cc0,
CmsWrapper = 0xfade0b01,
}
19 changes: 19 additions & 0 deletions src/installer/managed/Microsoft.NET.HostModel/MachO/CmsBlob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Runtime.InteropServices;

namespace Microsoft.NET.HostModel.MachO;

[StructLayout(LayoutKind.Sequential)]
internal struct CmsWrapperBlob
jtschuster marked this conversation as resolved.
Show resolved Hide resolved
{
private BlobMagic _magic;
private uint _length;

public static CmsWrapperBlob Empty = new CmsWrapperBlob
{
_magic = (BlobMagic)((uint)BlobMagic.CmsWrapper).MakeBigEndian(),
_length = 8u.MakeBigEndian()
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.NET.HostModel.MachO;

internal enum CodeDirectoryFlags : uint
{
Adhoc = 2,
}
Loading
Loading