Skip to content

Instantly share code, notes, and snippets.

@20chan
Created September 20, 2017 16:28
Show Gist options
  • Select an option

  • Save 20chan/a7fcc4d1edae1f9a45eb3dc7895831a7 to your computer and use it in GitHub Desktop.

Select an option

Save 20chan/a7fcc4d1edae1f9a45eb3dc7895831a7 to your computer and use it in GitHub Desktop.
Execute machine code in C#
using System;
using System.Runtime.InteropServices;
namespace AssemblySharp
{
class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, AllocationType flAllocationType, MemoryProtection flProtect);
[Flags]
public enum AllocationType
{
Commit = 0x1000,
Reserve = 0x2000,
Decommit = 0x4000,
Release = 0x8000,
Reset = 0x80000,
Physical = 0x400000,
TopDown = 0x100000,
WriteWatch = 0x200000,
LargePages = 0x20000000
}
[Flags]
public enum MemoryProtection
{
Execute = 0x10,
ExecuteRead = 0x20,
ExecuteReadWrite = 0x40,
ExecuteWriteCopy = 0x80,
NoAccess = 0x01,
ReadOnly = 0x02,
ReadWrite = 0x04,
WriteCopy = 0x08,
GuardModifierflag = 0x100,
NoCacheModifierflag = 0x200,
WriteCombineModifierflag = 0x400
}
const int
PAGE_READWRITE = 0x40,
PROCESS_VM_OPERATION = 0x0008,
PROCESS_VM_READ = 0x0010,
PROCESS_VM_WRITE = 0x0020;
const uint PAGE_EXECUTE_READWRITE = 0x40;
delegate int IntDelegate();
static void Main(string[] args)
{
byte[] code = { 0xb8, 0x01, 0x00, 0x00, 0x00, 0xc3 };
var buffer = VirtualAlloc(IntPtr.Zero, (uint)code.Length, AllocationType.Commit, MemoryProtection.ExecuteReadWrite);
Marshal.Copy(code, 0, buffer, code.Length);
var ptr = Marshal.GetDelegateForFunctionPointer<IntDelegate>(buffer);
Console.WriteLine(ptr());
Console.Read();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment