C#呼び出しシステムAPIを使用してメモリ注入を実現するコード

4782 ワード

 
  
//
using System.Runtime.InteropServices;
///
/// .. MEM_RESET , 0.
///

/// . PROCESS_VM_OPERATION
/// . NULL
/// . .
///
///
/// , 0。
[DllImport("kernel32.dll")] // API
public static extern int VirtualAllocEx(IntPtr process, int pAddress, int size, int type, int protect);
///
/// 。 ,
///

///
///
/// ( )。
///
///
///
[DllImport("kernel32.dll")]
public static extern int WriteProcessMemory(IntPtr process, int baseAddress, string buffer, int nSize, int lpNumberOfBytesWritten);
///
/// (DLL)
///

/// DLL DLL 。LoadLibrary GetModuleHandle 。
/// NULL , 。 , , 0。
/// , DLL , , 0。 , GetLastError。
[DllImport("kernel32.dll")]
public static extern int GetProcAddress(int hModule, string lpProcName);
///
///
///

///
/// , 。
[DllImport("kernel32.dll")]
public static extern int GetModuleHandleA(string moduleName);
///
/// ( : ).
///

///
/// , 0,
/// , 0, , 1M
///
///
/// (0  CREATE_SUSPENDED 0x00000004 , ResumeThread )
/// , , 0
/// , , 0
[DllImport("kernel32.dll")]
public static extern int CreateRemoteThread(IntPtr process, int threadAttributes, int stackSize, int startAddress, int parameter, int creationFlags, int threadid);
 
  
///
///
///

///
///
public Process GetProcessByName(string ProcessName)
{
//
Process[] pname = Process.GetProcesses();
//
foreach (Process name in pname)
{
//
if (name.ProcessName.ToLower().IndexOf(ProcessName) != -1)
return name;
}
return null;
}
 
  
public void killDll()
{
string dllName = "c:\\text.dll";
int dlllength = dllName.Length + 1;
//
Process processName = GetProcessByName("notepad");
// ,
if (processName != null)
{
// , , 0。
int baseaddress = VirtualAllocEx(processName.Handle, 0, dlllength, 4096, 4);
if (baseaddress == 0)
{
MessageBox.Show(" !");
return;
}
//
int result = WriteProcessMemory(processName.Handle, baseaddress, dllName, dlllength, 0);
if (result == 0)
{
MessageBox.Show(" !");
return;
}
// loadlibarary kernek32.dll
int procAddress = GetProcAddress(GetModuleHandleA("Kernel32"), "LoadLibraryA");
if (procAddress == 0)
{
MessageBox.Show(" !");
return;
}
// 。
result = CreateRemoteThread(processName.Handle, 0, 0, 0, baseaddress, 0, 0);
if (result == 0)
{
MessageBox.Show(" !");
return;
}
else
MessageBox.Show(" dll!");
}
}