Skip to content

Instantly share code, notes, and snippets.

@dr4k0nia
Last active September 12, 2021 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dr4k0nia/ca72c5ddef2b5072831026aeeb9806fd to your computer and use it in GitHub Desktop.
Save dr4k0nia/ca72c5ddef2b5072831026aeeb9806fd to your computer and use it in GitHub Desktop.
DynamicInvoke of native functions using GetProcAddress
using System.Diagnostics;
using System.Text;
using System;
using System.Runtime.InteropServices;
namespace Code_Projects
{
public static class DynamicInvokeExample
{
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint PVM(IntPtr ProcessHandle, ref IntPtr BaseAddress, ref uint numberOfBytes,
uint newProtect, out uint oldProtect);
public static IntPtr GetLoadedModuleAddress(string dllName)
{
var procModules = Process.GetCurrentProcess().Modules;
foreach (ProcessModule mod in procModules)
{
if (mod.ModuleName != dllName)
continue;
return mod.BaseAddress;
}
return IntPtr.Zero;
}
private static IntPtr GetFunctionPointer(string dllName, string functionName)
{
var hModule = GetLoadedModuleAddress(dllName);
return GetProcAddress(hModule, functionName);
}
public static void Protect()
{
string dllName = Encoding.UTF8.GetString(Convert.FromBase64String("bnRkbGwuZGxs")); // ntdll.dll
string functionName = Encoding.UTF8.GetString(Convert.FromBase64String("TnRQcm90ZWN0VmlydHVhbE1lbW9yeQ==")); // NtProtectVirtualMemory
var fPointer = GetFunctionPointer(dllName, functionName);
PVM pvm = Marshal.GetDelegateForFunctionPointer<PVM>(fPointer);
var p = Process.GetCurrentProcess();
var @base = p.MainModule.BaseAddress;
uint size = 0x3C;
pvm(p.Handle, ref @base, ref size, 0x04, out uint oldProtect);
Marshal.Copy(new byte[size], 0, @base, (int)size);
pvm(p.Handle, ref @base, ref size, oldProtect, out _);
}
}
}
@dr4k0nia
Copy link
Author

dr4k0nia commented Aug 3, 2021

This example invokes NtProtectVirtualMemory from ntdll.dll
The delegate PVM is specifically for NtProtectVirtualMemory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment