Use C # Call the system API to implement memory injection code

Source: Internet
Author: User

Copy codeThe Code is as follows: // first import the namespace
Using System. Runtime. InteropServices;
/// <Summary>
/// Reserve or open up a region in the virtual address space of the specified process... the memory region is initialized to 0 unless MEM_RESET is in use.
/// </Summary>
/// <Param name = "process"> handle of the process in which space is allocated. The handle must have PROCESS_VM_OPERATION access permission. </param>
/// <Param name = "pAddress"> address area to be obtained. Generally, it is automatically allocated using NULL. </param>
/// <Param name = "size"> size of the memory to be allocated. The Byte unit. Note that the actual memory size in the allocation is an integer multiple of the page memory size. </param>
/// <Param name = "type"> memory allocation type </param>
/// <Param name = "protect"> Memory Page Protection </param>
/// <Returns> If the execution succeeds, the first address of the allocated memory is returned. If the execution fails, 0 is returned. </Returns>
[DllImport ("kernel32.dll")] // declare an API Function
Public static extern int VirtualAllocEx (IntPtr process, int pAddress, int size, int type, int protect );
/// <Summary>
/// Write the memory area of a process. The portal must be accessible; otherwise, the Operation will fail.
/// </Summary>
/// <Param name = "process"> process Handle </param>
/// <Param name = "baseAddress"> first address of the memory to be written </param>
/// <Param name = "buffer"> pointer to the data to be written (the current data storage address ). </Param>
/// <Param name = "nSize"> Number of bytes to write. </Param>
/// <Param name = "lpNumberOfBytesWritten"> actual data length </param>
/// <Returns> non-zero indicates successful, and zero indicates failed </returns>
[DllImport ("kernel32.dll")]
Public static extern int WriteProcessMemory (IntPtr process, int baseAddress, string buffer, int nSize, int lpNumberOfBytesWritten );
/// <Summary>
/// Retrieve the function address of the output library in the specified dynamic link library (DLL)
/// </Summary>
/// <Param name = "hModule"> the DLL module handle contains the handle of the DLL module of this function. The LoadLibrary or GetModuleHandle function can return this handle. </Param>
/// <Param name = "lpProcName"> the function name contains the string ending with NULL or the ordinal value of the specified function. If this parameter is a ordinal value, it must be at the bottom of a word, and the height must be 0. </Param>
/// <Returns> If the call is successful, return the output function address in the DLL. If the call fails, return 0. For more error information, call the GetLastError function. </Returns>
[DllImport ("kernel32.dll")]
Public static extern int GetProcAddress (int hModule, string lpProcName );
/// <Summary>
/// Obtain the module handle of an application or dynamic link library
/// </Summary>
/// <Param name = "moduleName"> specify the module name, which is usually the same name as the module File name </param>
/// <Returns> If the execution is successful, the module handle is returned. Zero indicates failure </returns>
[DllImport ("kernel32.dll")]
Public static extern int GetModuleHandleA (string moduleName );
/// <Summary>
/// Create a thread that runs in the address space of another process (also known as creating a remote thread ).
/// </Summary>
/// <Param name = "process"> handle of the target process </param>
/// <Param name = "threadAttributes"> pointer to the thread's security description struct, which is generally set to 0, indicating that the default security level is used </param>
/// <Param name = "stackSize"> specifies the thread stack size. Generally, the value is set to 0, indicating that the default size is used. Generally, the value is 1 MB. </param>
/// <Param name = "startAddress"> address of the thread function </param>
/// <Param name = "parameter"> parameters passed to the thread function </param>
/// <Param name = "creationFlags"> thread creation method (0 indicates that create_suincluded 0x00000004 is run immediately after the thread is created and creation will not run until the ResumeThread function is called) </param>
/// <Param name = "threadid"> pointer to the created thread handle. If creation fails, this parameter is 0 </param>
/// <Returns> If the call succeeds, a new thread handle is returned. If the call fails, 0 is returned. </returns>
[DllImport ("kernel32.dll")]
Public static extern int CreateRemoteThread (IntPtr process, int threadAttributes, int stackSize, int startAddress, int parameter, int creationFlags, int threadid );

Copy codeThe Code is as follows: // <summary>
/// Obtain the process based on the process name
/// </Summary>
/// <Param name = "ProcessName"> process name </param>
/// <Returns> </returns>
Public Process GetProcessByName (string ProcessName)
{
// Obtain all processes
Process [] pname = Process. GetProcesses ();
// Process Traversal
Foreach (Process name in pname)
{
// If the process name is found
If (name. ProcessName. ToLower (). IndexOf (ProcessName )! =-1)
Return name;
}
Return null;
}

Copy codeThe Code is as follows: 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, the injection starts below
If (processName! = Null)
{
// Apply for memory space. If the execution succeeds, the first address of the allocated memory is returned. If the execution fails, the value 0 is returned.
Int baseaddress = VirtualAllocEx (processName. Handle, 0, dlllength, 4096, 4 );
If (baseaddress = 0)
{
MessageBox. Show ("An error occurred while applying for memory space! ");
Return;
}
// Write memory
Int result = WriteProcessMemory (processName. Handle, baseaddress, dllName, dlllength, 0 );
If (result = 0)
{
MessageBox. Show ("failed to write memory! ");
Return;
}
// Obtain the loadlibarary address in kernek32.dll
Int procAddress = GetProcAddress (GetModuleHandleA ("Kernel32"), "LoadLibraryA ");
If (procAddress = 0)
{
MessageBox. Show ("the function entry point cannot be obtained! ");
Return;
}
// Create a remote thread.
Result = CreateRemoteThread (processName. Handle, 0, 0, 0, baseaddress, 0, 0 );
If (result = 0)
{
MessageBox. Show ("failed to create remote thread! ");
Return;
}
Else
MessageBox. Show ("dll has been injected successfully! ");
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.