c++ 防止DLL被注入两次

pn9klfpd  于 2023-01-18  发布在  其他
关注(0)|答案(1)|浏览(233)

我正在做一个DLL在C++是注入到另一个程序。当注入一次以上的程序崩溃,所以我希望DLL首先检查它是否已经注入,如果是这样,它会做一些代码,如显示一个消息框或只是退出

gcxthw6b

gcxthw6b1#

这可以使用EnumProcessModules来完成

BOOL isInjected() {
        const char ProcessName = "Process.exe"; 
        std::string DllName = "MyDll.dll"; 

        DWORD dwProcessId = NULL;
        HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if (hSnapshot == INVALID_HANDLE_VALUE)
            return false;

        PROCESSENTRY32 pe{};
        pe.dwSize = sizeof(PROCESSENTRY32);
        if (Process32First(hSnapshot, &pe))
        {
            do
            {
                if (_tcsicmp(pe.szExeFile, _T(ProcessName)) == 0)
                {
                    dwProcessId = pe.th32ProcessID;
                    break;
                }
            } while (Process32Next(hSnapshot, &pe));
        }

        CloseHandle(hSnapshot);

        HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessId);
        if (hProcess == NULL)
        {
            return false;
        }

        HMODULE hMods[1024];
        DWORD cbNeeded;
        if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
        {
            int amount = 0;
            for (unsigned int i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
            {
                TCHAR szModName[MAX_PATH];
                if (GetModuleFileNameEx(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR)))
                {
                    std::string str1 = szModName;

                    if (str1.find(DllName) != std::string::npos) amount++;
                }
            }
            if (amount >= 2) return true;
        }

        return false;
    }

相关问题