Skip to content

Assemblies returned from AppDomain.AssemblyResolve are checked for matching strong name #101029

Closed
@reflectronic

Description

@reflectronic

Reproduction

Make a dummy project without strong-name signing:

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <AssemblyName>Newtonsoft.Json</AssemblyName>
        <AssemblyVersion>15.0.0.0</AssemblyVersion>
    </PropertyGroup>

</Project>
namespace Newtonsoft.Json.Linq
{
    public class JArray
    {
        public JArray(params object[] values) { }

        public override string ToString() => "Surprise!";
    }
}

Then, the project to demonstrate the error:

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <OutputType>Exe</OutputType>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Newtonsoft.Json" Version="13.0.3" ExcludeAssets="runtime" />
        <!-- Change path to wherever you decide to put it... -->
        <None Include="../Newtonsoft.Json/bin/Debug/net8.0/Newtonsoft.Json.dll" CopyToOutputDirectory="PreserveNewest" />
    </ItemGroup>

</Project>
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using Newtonsoft.Json.Linq;

// #1
// Assembly.LoadFrom("Newtonsoft.Json.dll");

// #2
// AppDomain.CurrentDomain.AssemblyResolve += (_, _) =>
// {
//     return Assembly.LoadFrom("Newtonsoft.Json.dll");
// };

Run();

[MethodImpl(MethodImplOptions.NoInlining)]
void Run()
{
    Console.WriteLine(new JArray(1, 2, 3).ToString());
}

Run the project. It should fail with:

System.IO.FileNotFoundException: 'Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. The system cannot find the file specified.'

This is expected.

Uncomment the code labeled '#1'. The code should run with output:

Surprise!

This is also expected, since .NET Core should ignore strong names for the purpose of assembly binding.

Re-comment that code, and now uncomment the code labeled '#2'. The code will fail with:

System.IO.FileLoadException: 'Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. A strongly-named assembly is required. (0x80131044)'

This is not expected—the code should run successfully as it did in the previous example.

Commentary

This code in AppDomain::RaiseAssemblyResolveEvent seems suspicious:

// Check that the public key token matches the one specified in the spec
// MatchPublicKeys throws as appropriate
pSpec->MatchPublicKeys(pAssembly);

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions