Using C to call system API to implement memory injection code

  • 2020-05-07 20:17:57
  • OfStack

 
// First, import the namespace  
using System.Runtime.InteropServices; 
/// <summary> 
///  Holds or opens in the virtual address space of the specified process 1 Section of the area .. unless MEM_RESET Is used, otherwise the memory area is initialized to 0. 
/// </summary> 
/// <param name="process"> Handle to the process in which space is allocated . This handle must be owned PROCESS_VM_OPERATION Access permissions </param> 
/// <param name="pAddress"> The address area you want to get .1 As with NULL Automatically assigned </param> 
/// <param name="size"> The amount of memory to be allocated . Byte units . Pay attention to the actual score   The allocated memory size is an integer multiple of the page memory size </param> 
/// <param name="type"> Type of memory allocation </param> 
/// <param name="protect"> Memory page protection </param> 
/// <returns> Returns the first address of the allocated memory on success and fails 0 . </returns> 
[DllImport("kernel32.dll")] // The statement API function  
public static extern int VirtualAllocEx(IntPtr process, int pAddress, int size, int type, int protect); 
/// <summary> 
///  Write a 1 The memory area of the process. The entry area must be accessible or the operation will fail  
/// </summary> 
/// <param name="process"> Process to handle </param> 
/// <param name="baseAddress"> The first address of memory to write </param> 
/// <param name="buffer"> A pointer to the data to be written ( The current address of the data ) . </param> 
/// <param name="nSize"> Number of bytes to write. </param> 
/// <param name="lpNumberOfBytesWritten"> The length of the actual data </param> 
/// <returns> Non-zero means success and zero means failure </returns> 
[DllImport("kernel32.dll")] 
public static extern int WriteProcessMemory(IntPtr process, int baseAddress, string buffer, int nSize, int lpNumberOfBytesWritten); 
/// <summary> 
///  Retrieves the specified dynamic link library (DLL) The output library function address in  
/// </summary> 
/// <param name="hModule"> DLL Handle to the module   Contains this function DLL Handle to the module. LoadLibrary or GetModuleHandle The function can return this handle. </param> 
/// <param name="lpProcName"> The function name   Contains the name of the function NULL The ending string, or the ordinal value of the specified function. If this parameter is 1 It has to be 1 The base byte of a word, the high byte must be 0 . </param> 
/// <returns> Call successful, return DLL Output function address, call failed, return 0 . Get into the 1 Step error message, calling the function GetLastError . </returns> 
[DllImport("kernel32.dll")] 
public static extern int GetProcAddress(int hModule, string lpProcName); 
/// <summary> 
///  To obtain 1 A module handle to an application or dynamically linked library  
/// </summary> 
/// <param name="moduleName"> Specify the module name, which is usually the same as the module file name 1 A name </param> 
/// <returns> If the execution succeeds, the module handle is returned. Zero means failure </returns> 
[DllImport("kernel32.dll")] 
public static extern int GetModuleHandleA(string moduleName); 
/// <summary> 
///  create 1 Threads running in the address space of other processes ( Also known as : Create a remote thread ). 
/// </summary> 
/// <param name="process"> Handle to the target process </param> 
/// <param name="threadAttributes"> A pointer to a thread's safe description structure, 1 A set to 0 Represents the use of the default security level </param> 
/// <param name="stackSize"> Thread stack size, 1 A set to 0 , means the default size is used. 1 As for the 1M</param> 
/// <param name="startAddress"> The address of the thread function </param> 
/// <param name="parameter"> Parameter passed to the thread function </param> 
/// <param name="creationFlags"> How threads are created (0 After the thread is created  Run immediately  CREATE_SUSPENDED 0x00000004 Created by hanging   Creation does not run until invoked  ResumeThread function )</param> 
/// <param name="threadid"> A pointer to the handle to the created thread , If the creation fails , The parameters for 0</param> 
/// <returns> If the call succeeds , Returns a new thread handle , Failure to return 0</returns> 
[DllImport("kernel32.dll")] 
public static extern int CreateRemoteThread(IntPtr process, int threadAttributes, int stackSize, int startAddress, int parameter, int creationFlags, int threadid); 

 
/// <summary> 
///  Gets the process by its name  
/// </summary> 
/// <param name="ProcessName"> Process name </param> 
/// <returns></returns> 
public Process GetProcessByName(string ProcessName) 
{ 
// Get all processes  
Process[] pname = Process.GetProcesses(); 
// Traversal process  
foreach (Process name in pname) 
{ 
// If the process name is found   return  
if (name.ProcessName.ToLower().IndexOf(ProcessName) != -1) 
return name; 
} 
return null; 
} 

 
public void killDll() 
{ 
string dllName = "c:\\text.dll"; 
int dlllength = dllName.Length + 1; 
// Take notepad as an example  
Process processName = GetProcessByName("notepad"); 
// If the notepad process is found, then the injection begins  
if (processName != null) 
{ 
// Request memory space , Successful execution returns the first address of the allocated memory 0 .  
int baseaddress = VirtualAllocEx(processName.Handle, 0, dlllength, 4096, 4); 
if (baseaddress == 0) 
{ 
MessageBox.Show(" Application for memory space failed! "); 
return; 
} 
// Write a memory  
int result = WriteProcessMemory(processName.Handle, baseaddress, dllName, dlllength, 0); 
if (result == 0) 
{ 
MessageBox.Show(" Write memory failed! "); 
return; 
} 
// achieve loadlibarary in kernek32.dll address  
int procAddress = GetProcAddress(GetModuleHandleA("Kernel32"), "LoadLibraryA"); 
if (procAddress == 0) 
{ 
MessageBox.Show(" Cannot get the entry point of the function! "); 
return; 
} 
// Create a remote thread.  
result = CreateRemoteThread(processName.Handle, 0, 0, 0, baseaddress, 0, 0); 
if (result == 0) 
{ 
MessageBox.Show(" Remote thread creation failed! "); 
return; 
} 
else 
MessageBox.Show(" Successfully injected dll!"); 
} 
} 

Related articles: