Skip to content

Commit

Permalink
Merge pull request #290 from Washi1337/development
Browse files Browse the repository at this point in the history
4.10.0
  • Loading branch information
Washi1337 committed Apr 9, 2022
2 parents 4ac45c3 + fb3516a commit 388a36e
Show file tree
Hide file tree
Showing 99 changed files with 2,480 additions and 105 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

[*]
charset = utf-8
end_of_line = lf
end_of_line = crlf
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
Expand Down
15 changes: 12 additions & 3 deletions AsmResolver.sln
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,18 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TlsTest", "test\TestBinarie
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CallManagedExport", "test\TestBinaries\Native\CallManagedExport\CallManagedExport.vcxproj", "{40483E28-C703-4933-BA5B-9512EF6E6A21}"
EndProject
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "HelloWorldVB", "test\TestBinaries\DotNet\HelloWorldVB\HelloWorldVB.vbproj", "{CF6A7E02-37DC-4963-AC14-76D74ADCD87A}"
EndProject
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "ClassLibraryVB", "test\TestBinaries\DotNet\ClassLibraryVB\ClassLibraryVB.vbproj", "{2D1DF5DA-7367-4490-B3F0-B996348E150B}"
Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "HelloWorldVB", "test\TestBinaries\DotNet\HelloWorldVB\HelloWorldVB.vbproj", "{CF6A7E02-37DC-4963-AC14-76D74ADCD87A}"
EndProject
Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "ClassLibraryVB", "test\TestBinaries\DotNet\ClassLibraryVB\ClassLibraryVB.vbproj", "{2D1DF5DA-7367-4490-B3F0-B996348E150B}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{66C7E95F-0C1A-466E-988A-C84D5542458B}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
.gitignore = .gitignore
CONTRIBUTING.md = CONTRIBUTING.md
LICENSE.md = LICENSE.md
README.md = README.md
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<RepositoryUrl>https://github.com/Washi1337/AsmResolver</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<LangVersion>10</LangVersion>
<Version>4.9.0</Version>
<Version>4.10.0</Version>
</PropertyGroup>

</Project>
19 changes: 12 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
AsmResolver
===========

[![Master branch build status](https://img.shields.io/appveyor/ci/Washi1337/AsmResolver/master.svg)](https://ci.appveyor.com/project/Washi1337/asmresolver/branch/master) [![Nuget feed](https://img.shields.io/nuget/v/AsmResolver.svg)](https://www.nuget.org/packages/AsmResolver/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Documentation Status](https://readthedocs.org/projects/asmresolver/badge/?version=latest)](https://asmresolver.readthedocs.io/en/latest/?badge=latest)
[![Master branch build status](https://img.shields.io/appveyor/ci/Washi1337/AsmResolver/master.svg)](https://ci.appveyor.com/project/Washi1337/asmresolver/branch/master)
[![Nuget feed](https://img.shields.io/nuget/v/AsmResolver.svg)](https://www.nuget.org/packages/AsmResolver/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Documentation Status](https://readthedocs.org/projects/asmresolver/badge/?version=latest)](https://asmresolver.readthedocs.io/en/latest/?badge=latest)
[![Discord](https://img.shields.io/discord/961647807591243796.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/Y7DTBkbhJJ)

AsmResolver is a PE inspection library allowing .NET programmers to read, modify and write executable files. This includes .NET as well as native images. The library exposes high-level representations of the PE, while still allowing the user to access low-level structures.

Expand Down Expand Up @@ -53,19 +57,20 @@ Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on general workflow and code style.


Found a bug or have questions?
------------------------------
Please use the [issue tracker](https://github.com/Washi1337/AsmResolver/issues). Try to be as descriptive as possible.

You can also join the [Discord](https://discord.gg/Y7DTBkbhJJ) to engage more directly with the community.

Acknowledgements
----------------

AsmResolver started out as a hobby project, but has grown into a community project with various contributors. Without these people, AsmResolver would not have been where it is today!

- Special thanks to all the people who contributed [directly with code commits](https://github.com/Washi1337/AsmResolver/graphs/contributors).

- Another big thank you to all the people that suggested new features, provided feedback on the API design, have done extensive testing, and/or reported bugs on the [issue board](https://github.com/Washi1337/AsmResolver/issues), by e-mail, or through DMs.
- Another big thank you to all the people that suggested new features, provided feedback on the API design, have done extensive testing, and/or reported bugs on the [issue board](https://github.com/Washi1337/AsmResolver/issues), by e-mail, or through DMs.

If you feel you have been under-represented in these acknowledgements, feel free to contact me.


Found a bug or have questions?
------------------------------
Please use the [issue tracker](https://github.com/Washi1337/AsmResolver/issues). Try to be as descriptive as possible.

4 changes: 2 additions & 2 deletions appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
- master

image: Visual Studio 2022
version: 4.9.0-master-build.{build}
version: 4.10.0-master-build.{build}
configuration: Release

skip_commits:
Expand Down Expand Up @@ -33,7 +33,7 @@
- development

image: Visual Studio 2022
version: 4.9.0-dev-build.{build}
version: 4.10.0-dev-build.{build}
configuration: Release

skip_commits:
Expand Down
176 changes: 176 additions & 0 deletions docs/dotnet/bundles.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
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:

.. code-block:: csharp
using AsmResolver.DotNet.Bundles;
Creating Bundles
----------------

.NET bundles are represented using the ``BundleManifest`` class. Creating new bundles can be done using any of the constructors:

.. code-block:: csharp
var manifest = new BundleManifest(majorVersionNumber: 6);
The major version number refers to the file format that should be used when saving the manifest. Below an overview of the values that are recognized by the CLR:

+----------------------+----------------------------+
| .NET Version Number | Bundle File Format Version |
+======================+============================+
| .NET Core 3.1 | 1 |
+----------------------+----------------------------+
| .NET 5.0 | 2 |
+----------------------+----------------------------+
| .NET 6.0 | 6 |
+----------------------+----------------------------+

To create a new bundle with a specific bundle identifier, use the overloaded constructor

.. code-block:: csharp
var manifest = new BundleManifest(6, "MyBundleID");
It is also possible to change the version number as well as the bundle ID later, since these values are exposed as mutable properties ``MajorVersion`` and ``BundleID``

.. code-block:: csharp
manifest.MajorVersion = 6;
manifest.BundleID = manifest.GenerateDeterministicBundleID();
.. note::

If ``BundleID`` is left unset (``null``), it will be automatically assigned a new one using ``GenerateDeterministicBundleID`` upon writing.


Reading Bundles
---------------

Reading and extracting existing bundle manifests from an executable can be done by using one of the ``FromXXX`` methods:

.. code-block:: csharp
var manifest = BundleManifest.FromFile(@"C:\Path\To\Executable.exe");
.. code-block:: csharp
byte[] contents = ...
var manifest = BundleManifest.FromBytes(contents);
.. code-block:: csharp
IDataSource contents = ...
var manifest = BundleManifest.FromDataSource(contents);
Similar to the official .NET bundler and extractor, the methods above locate the bundle in the file by looking for a specific signature first. However, official implementations of the application hosting program itself actually do not verify or use this signature in any shape or form. This means that a third party can replace or remove this signature, or write their own implementation of an application host that does not adhere to this standard, and thus throw off static analysis of the file.

AsmResolver does not provide built-in alternative heuristics for finding the right start address of the bundle header. However, it is possible to implement one yourself and provide the resulting start address in one of the overloads of the ``FromXXX`` methods:

.. code-block:: csharp
byte[] contents = ...
ulong bundleAddress = ...
var manifest = BundleManifest.FromBytes(contents, bundleAddress);
.. code-block:: csharp
IDataSource contents = ...
ulong bundleAddress = ...
var manifest = BundleManifest.FromDataSource(contents, bundleAddress);
Writing Bundles
---------------

Constructing new bundled executable files requires a template file that AsmResolver can base the final output on. This is similar how .NET compilers themselves do this as well. By default, the .NET SDK installs template binaries in one of the following directories:

- ``<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``:

.. code-block:: csharp
BundleManifest manifest = ...
manifest.WriteUsingTemplate(
@"C:\Path\To\Output\File.exe",
new BundlerParameters(
appHostTemplatePath: @"C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Host.win-x64\6.0.0\runtimes\win-x64\native\apphost.exe",
appBinaryPath: @"HelloWorld.dll"));
Typically on Windows, use an ``apphost.exe`` template if you want to construct a native binary that is framework dependent, and ``singlefilehost.exe`` for a fully self-contained binary. On Linux, use the ``apphost`` and ``singlefilehost`` ELF equivalents.

For bundle executable files targeting Windows, it may be required to copy over some values from the original PE file into the final bundle executable file. Usually these values include fields from the PE headers (such as the executable's sub-system target) and Win32 resources (such as application icons and version information). AsmResolver can automatically update these headers by specifying a source image to pull this data from in the ``BundlerParameters``:

.. code-block:: csharp
BundleManifest manifest = ...
manifest.WriteUsingTemplate(
@"C:\Path\To\Output\File.exe",
new BundlerParameters(
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.


Managing Files
--------------

Files in a bundle are represented using the ``BundleFile`` class, and are exposed by the ``BundleManifest.Files`` property. Both the class as well as the list itself is fully mutable, and thus can be used to add, remove or modify files in the bundle.

Creating a new file can be done using the constructors:

.. code-block:: csharp
var newFile = new BundleFile(
relativePath: "HelloWorld.dll",
type: BundleFileType.Assembly,
contents: System.IO.File.ReadAllBytes(@"C:\Binaries\HelloWorld.dll"));
manifest.Files.Add(newFile);
It is also possible to iterate over all files and inspect their contents using ``GetData``:

.. code-block:: csharp
foreach (var file in manifest.Files)
{
string path = file.RelativePath;
byte[] contents = file.GetData();
Console.WriteLine($"Extracting {path}...");
System.IO.File.WriteAllBytes(path, contents);
}
Changing the contents of an existing file can be done using the ``Contents`` property.

.. code-block:: csharp
BundleFile file = ...
file.Contents = new DataSegment(new byte[] { 1, 2, 3, 4 });
If the bundle manifest is put into a single-file host template (e.g. ``singlefilehost.exe``), then files can also be compressed or decompressed:

.. code-block:: csharp
file.Compress();
// file.Contents now contains the compressed version of the data and file.IsCompressed = true
file.Decompress();
// file.Contents now contains the decompressed version of the data and file.IsCompressed = false
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,5 @@ Table of Contents:
dotnet/cloning
dotnet/token-allocation
dotnet/type-memory-layout
dotnet/bundles
dotnet/advanced-pe-image-building.rst
3 changes: 3 additions & 0 deletions src/AsmResolver.DotNet/AssemblyDefinition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,9 @@ protected virtual IList<ModuleDefinition> GetModules()
return _publicKeyToken;
}

/// <inheritdoc />
public override bool IsImportedInModule(ModuleDefinition module) => ManifestModule == module;

/// <inheritdoc />
public override AssemblyDefinition Resolve() => this;

Expand Down
7 changes: 6 additions & 1 deletion src/AsmResolver.DotNet/AssemblyDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
using AssemblyHashAlgorithm = AsmResolver.PE.DotNet.Metadata.Tables.Rows.AssemblyHashAlgorithm;

namespace AsmResolver.DotNet
{
/// <summary>
/// Provides a base implementation for describing a self-describing .NET assembly hosted by a common language runtime (CLR).
/// </summary>
public abstract class AssemblyDescriptor : MetadataMember, IHasCustomAttribute, IFullNameProvider
public abstract class AssemblyDescriptor : MetadataMember, IHasCustomAttribute, IFullNameProvider, IImportable
{
private const int PublicKeyTokenLength = 8;

Expand Down Expand Up @@ -212,6 +214,9 @@ public IList<CustomAttribute> CustomAttributes
/// <inheritdoc />
public override string ToString() => FullName;

/// <inheritdoc />
public abstract bool IsImportedInModule(ModuleDefinition module);

/// <summary>
/// Computes the token of a public key using the provided hashing algorithm.
/// </summary>
Expand Down
3 changes: 3 additions & 0 deletions src/AsmResolver.DotNet/AssemblyReference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@ public AssemblyReference(AssemblyDescriptor descriptor)
/// </remarks>
protected virtual byte[]? GetHashValue() => null;

/// <inheritdoc />
public override bool IsImportedInModule(ModuleDefinition module) => Module == module;

/// <inheritdoc />
public override AssemblyDefinition? Resolve() => Module?.MetadataResolver.AssemblyResolver.Resolve(this);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace AsmResolver.DotNet.Builder.Metadata.Blob
public class BlobStreamBuffer : IMetadataStreamBuffer
{
private readonly MemoryStream _rawStream = new();
private readonly IBinaryStreamWriter _writer;
private readonly BinaryStreamWriter _writer;
private readonly Dictionary<byte[], uint> _blobs = new(ByteArrayEqualityComparer.Instance);

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace AsmResolver.DotNet.Builder.Metadata.Guid
public class GuidStreamBuffer : IMetadataStreamBuffer
{
private readonly MemoryStream _rawStream = new();
private readonly IBinaryStreamWriter _writer;
private readonly BinaryStreamWriter _writer;
private readonly Dictionary<System.Guid, uint> _guids = new();

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace AsmResolver.DotNet.Builder.Metadata.UserStrings
public class UserStringsStreamBuffer : IMetadataStreamBuffer
{
private readonly MemoryStream _rawStream = new();
private readonly IBinaryStreamWriter _writer;
private readonly BinaryStreamWriter _writer;
private readonly Dictionary<string, uint> _strings = new();

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace AsmResolver.DotNet.Builder.Resources
public class DotNetResourcesDirectoryBuffer
{
private readonly MemoryStream _rawStream = new();
private readonly IBinaryStreamWriter _writer;
private readonly BinaryStreamWriter _writer;
private readonly Dictionary<byte[], uint> _dataOffsets = new(ByteArrayEqualityComparer.Instance);

/// <summary>
Expand Down

0 comments on commit 388a36e

Please sign in to comment.