Skip to content

Instantly share code, notes, and snippets.

@tyranid
Created February 3, 2019 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyranid/fff0d667d6b8f6871f302ac7bf3b00ce to your computer and use it in GitHub Desktop.
Save tyranid/fff0d667d6b8f6871f302ac7bf3b00ce to your computer and use it in GitHub Desktop.
Change main module path of the current executable. Can be used to spoof Process::MainModule information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ChangeModulePath
{
class Program
{
[StructLayout(LayoutKind.Sequential)]
struct LIST_ENTRY
{
public IntPtr Flink;
public IntPtr Blink;
}
[StructLayout(LayoutKind.Sequential)]
struct UNICODE_STRING
{
public ushort Length;
public ushort MaximumLength;
public IntPtr Buffer;
public override string ToString()
{
return Marshal.PtrToStringUni(Buffer, Length / 2);
}
public UNICODE_STRING(string str)
{
Length = (ushort)(str.Length * 2);
MaximumLength = (ushort)((str.Length + 1) * 2);
Buffer = Marshal.StringToHGlobalUni(str + "\0");
}
}
[StructLayout(LayoutKind.Sequential)]
struct LDR_DATA_TABLE_ENTRY
{
public LIST_ENTRY InLoadOrderLinks;
public LIST_ENTRY InMemoryOrderLinks;
public LIST_ENTRY InInitializationOrderLinks;
public IntPtr DllBase;
public IntPtr EntryPoint;
public int SizeOfImage;
public UNICODE_STRING FullDllName;
public UNICODE_STRING BaseDllName;
}
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode)]
delegate void LdrEnumCallback(ref LDR_DATA_TABLE_ENTRY Entry, IntPtr Context, out bool StopEnum);
[DllImport("ntdll.dll")]
static extern int LdrEnumerateLoadedModules(
bool ReservedFlag,
LdrEnumCallback EnumProc,
IntPtr Context
);
static void EnumCallback(ref LDR_DATA_TABLE_ENTRY Entry, IntPtr Context, out bool StopEnum)
{
string location = typeof(Program).Assembly.Location;
if (location.Equals(Entry.FullDllName.ToString(), StringComparison.OrdinalIgnoreCase))
{
StopEnum = true;
Console.WriteLine("Found main module entry");
Entry.FullDllName = new UNICODE_STRING(@"c:\blah\blah.exe");
Entry.BaseDllName = new UNICODE_STRING(@"blah.exe");
}
else
{
StopEnum = false;
Console.WriteLine("Not main {0}", Entry.FullDllName);
}
}
static void Main(string[] args)
{
try
{
LdrEnumerateLoadedModules(false, EnumCallback, IntPtr.Zero);
Console.WriteLine("PID: {0}", Process.GetCurrentProcess().Id);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment