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

Repackage AppHost files #424

Merged
merged 4 commits into from
Mar 19, 2023
Merged
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
36 changes: 31 additions & 5 deletions docs/dotnet/bundles.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ AppHost / SingleFileHost Bundles

Since the release of .NET Core 3.1, it is possible to deploy .NET assemblies as a single binary. These files are executables that do not contain a traditional .NET metadata header, and run natively on the underlying operating system via a platform-specific application host bootstrapper.

AsmResolver supports extracting the embedded files from these types of binaries. Additionally, given an application host template provided by the .NET SDK, AsmResolver also supports constructing new bundles as well. All relevant code is found in the following namespace:
AsmResolver supports extracting the embedded files from these types of binaries. Additionally, given the original file or an application host template provided by the .NET SDK, AsmResolver also supports constructing new bundles as well. All relevant code is found in the following namespace:

.. code-block:: csharp

Expand Down Expand Up @@ -96,14 +96,14 @@ Constructing new bundled executable files requires a template file that AsmResol
- ``<DOTNET-INSTALLATION-PATH>/sdk/<version>/AppHostTemplate``
- ``<DOTNET-INSTALLATION-PATH>/packs/Microsoft.NETCore.App.Host.<runtime-identifier>/<version>/runtimes/<runtime-identifier>/native``

Using this template file, it is then possible to write a new bundled executable file using ``WriteUsingTemplate``:
Using this template file, it is then possible to write a new bundled executable file using ``WriteUsingTemplate`` and the ``BundlerParameters::FromTemplate`` method:

.. code-block:: csharp

BundleManifest manifest = ...
manifest.WriteUsingTemplate(
@"C:\Path\To\Output\File.exe",
new BundlerParameters(
BundlerParameters.FromTemplate(
appHostTemplatePath: @"C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Host.win-x64\6.0.0\runtimes\win-x64\native\apphost.exe",
appBinaryPath: @"HelloWorld.dll"));

Expand All @@ -117,12 +117,38 @@ For bundle executable files targeting Windows, it may be required to copy over s
BundleManifest manifest = ...
manifest.WriteUsingTemplate(
@"C:\Path\To\Output\File.exe",
new BundlerParameters(
BundlerParameters.FromTemplate(
appHostTemplatePath: @"C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Host.win-x64\6.0.0\runtimes\win-x64\native\apphost.exe",
appBinaryPath: @"HelloWorld.dll",
imagePathToCopyHeadersFrom: @"C:\Path\To\Original\HelloWorld.exe"));

``BundleManifest`` also defines other ```WriteUsingTemplate`` overloads taking ``byte[]``, ``IDataSource`` or ``IPEImage`` instances instead of paths.

If you do not have access to a template file (e.g., if the SDK is not installed) but have another existing PE file that was packaged in a similar fashion, it is then possible to use this file as a template instead by extracting the bundler parameters using the ``BundlerParameters::FromExistingBundle`` method. This is in particularly useful when trying to patch existing AppHost bundles:

.. code-block:: csharp

string inputPath = @"C:\Path\To\Bundled\HelloWorld.exe";
string outputPath = Path.ChangeExtension(inputPath, ".patched.exe");

// Read manifest.
var manifest = BundleManifest.FromFile(inputPath);

/* ... Make changes to manifest and its files ... */

// Repackage bundle using existing bundle as template.
manifest.WriteUsingTemplate(
outputPath,
BundlerParameters.FromExistingBundle(
originalFile: inputPath,
appBinaryPath: mainFile.RelativePath));


.. warning::

The ``BundlerParameters.FromExistingBundle`` method applies heuristics on the input file to determine the parameters for patching the input file. As heuristics are not perfect, this is not guaranteed to always work.


``BundleManifest`` and ``BundlerParameters`` also define overloads of the ``WriteUsingTemplate`` and ``FromTemplate`` / ``FromExistingBundle`` respectively, taking ``byte[]``, ``IDataSource`` or ``IPEImage`` instances instead of file paths.


Managing Files
Expand Down
25 changes: 15 additions & 10 deletions src/AsmResolver.DotNet/Bundles/BundleManifest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using AsmResolver.IO;
using AsmResolver.PE.File;
using AsmResolver.PE.File.Headers;
using AsmResolver.PE.Win32Resources;
using AsmResolver.PE.Win32Resources.Builder;

namespace AsmResolver.DotNet.Bundles
Expand All @@ -28,9 +29,6 @@ public class BundleManifest
0xee, 0x3b, 0x2d, 0xce, 0x24, 0xb3, 0x6a, 0xae
};

private static readonly byte[] AppBinaryPathPlaceholder =
Encoding.UTF8.GetBytes("c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2");

private IList<BundleFile>? _files;

/// <summary>
Expand Down Expand Up @@ -194,7 +192,7 @@ public static BundleManifest FromDataSource(IDataSource source, ulong offset)
/// <returns>The read manifest.</returns>
public static BundleManifest FromReader(BinaryStreamReader reader) => new SerializedBundleManifest(reader);

private static long FindInFile(IDataSource source, byte[] data)
internal static long FindInFile(IDataSource source, byte[] needle)
{
// Note: For performance reasons, we read data from the data source in blocks, such that we avoid
// virtual-dispatch calls and do the searching directly on a byte array instead.
Expand All @@ -206,12 +204,12 @@ private static long FindInFile(IDataSource source, byte[] data)
{
int read = source.ReadBytes(start, buffer, 0, buffer.Length);

for (int i = sizeof(ulong); i < read - data.Length; i++)
for (int i = sizeof(ulong); i < read - needle.Length; i++)
{
bool fullMatch = true;
for (int j = 0; fullMatch && j < data.Length; j++)
for (int j = 0; fullMatch && j < needle.Length; j++)
{
if (buffer[i + j] != data[j])
if (buffer[i + j] != needle[j])
fullMatch = false;
}

Expand Down Expand Up @@ -317,6 +315,7 @@ public void WriteUsingTemplate(Stream outputStream, in BundlerParameters paramet
/// <param name="parameters">The parameters to use for bundling all files into a single executable.</param>
public void WriteUsingTemplate(IBinaryStreamWriter writer, BundlerParameters parameters)
{
// Verify entry point assembly exists within the bundle and is a correct length.
var appBinaryEntry = Files.FirstOrDefault(f => f.RelativePath == parameters.ApplicationBinaryPath);
if (appBinaryEntry is null)
throw new ArgumentException($"Application {parameters.ApplicationBinaryPath} does not exist within the bundle.");
Expand All @@ -325,6 +324,7 @@ public void WriteUsingTemplate(IBinaryStreamWriter writer, BundlerParameters par
if (appBinaryPathBytes.Length > 1024)
throw new ArgumentException("Application binary path cannot exceed 1024 bytes.");

// Patch headers when necessary.
if (!parameters.IsArm64Linux)
EnsureAppHostPEHeadersAreUpToDate(ref parameters);

Expand All @@ -333,21 +333,26 @@ public void WriteUsingTemplate(IBinaryStreamWriter writer, BundlerParameters par
if (signatureAddress == -1)
throw new ArgumentException("AppHost template does not contain the bundle signature.");

long appBinaryPathAddress = FindInFile(appHostTemplateSource, AppBinaryPathPlaceholder);
long appBinaryPathAddress = FindInFile(appHostTemplateSource, parameters.PathPlaceholder);
if (appBinaryPathAddress == -1)
throw new ArgumentException("AppHost template does not contain the application binary path placeholder.");

// Write template.
writer.WriteBytes(parameters.ApplicationHostTemplate);

// Append manifest.
writer.Offset = writer.Length;
ulong headerAddress = WriteManifest(writer, parameters.IsArm64Linux);

// Update header address in apphost template.
writer.Offset = (ulong) signatureAddress - sizeof(ulong);
writer.WriteUInt64(headerAddress);

// Replace binary path placeholder with actual path.
writer.Offset = (ulong) appBinaryPathAddress;
writer.WriteBytes(appBinaryPathBytes);
if (AppBinaryPathPlaceholder.Length > appBinaryPathBytes.Length)
writer.WriteZeroes(AppBinaryPathPlaceholder.Length - appBinaryPathBytes.Length);
if (parameters.PathPlaceholder.Length > appBinaryPathBytes.Length)
writer.WriteZeroes(parameters.PathPlaceholder.Length - appBinaryPathBytes.Length);
}

private static void EnsureAppHostPEHeadersAreUpToDate(ref BundlerParameters parameters)
Expand Down
Loading