From 62bd0eaa6a2160cd9e0991ec24f1ab128da696f9 Mon Sep 17 00:00:00 2001 From: Rutherther Date: Thu, 5 Jan 2023 16:23:09 +0100 Subject: [PATCH] feat(injector): inject nethost.dll prior to Inject dll to verify the injection won't fail on missing nethost --- src/Inject/NosSmooth.Injector/NosInjector.cs | 38 ++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/Inject/NosSmooth.Injector/NosInjector.cs b/src/Inject/NosSmooth.Injector/NosInjector.cs index 108b1b7..0787c19 100644 --- a/src/Inject/NosSmooth.Injector/NosInjector.cs +++ b/src/Inject/NosSmooth.Injector/NosInjector.cs @@ -5,6 +5,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; +using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Text; @@ -88,6 +89,19 @@ public class NosInjector using var injector = new Reloaded.Injector.Injector(process); var memory = new ExternalMemory(process); + var netHostInjectionResult = InjectNetHostDll + ( + injector, + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), + System.IO.Path.GetDirectoryName(dllPath), + System.IO.Path.GetDirectoryName(process.MainModule?.FileName) + ); + + if (!netHostInjectionResult.IsSuccess) + { + return netHostInjectionResult; + } + var directoryName = Path.GetDirectoryName(dllPath); if (directoryName is null) { @@ -160,6 +174,30 @@ public class NosInjector } } + private Result InjectNetHostDll(Reloaded.Injector.Injector injector, params string?[] pathsToSearch) + { + string? foundPath = pathsToSearch + .Select(x => Path.Join(x, "nethost.dll")) + .FirstOrDefault(File.Exists); + + if (foundPath is null) + { + return new NotFoundError + ( + "Could not find nethost.dll to inject (tried to look in executing process directory, injector directory, target process directory)" + ); + } + + var handle = injector.Inject(foundPath); + + if (handle == 0) + { + return new InjectionFailedError(foundPath, "Only the devil knows why this happened."); + } + + return Result.FromSuccess(); + } + private ManagedMemoryAllocation AllocateString(IMemory memory, string str) { var bytes = Encoding.Unicode.GetBytes(str); -- 2.48.1