【问题标题】:CreateRemoteThread says file doesn't exist, but it DOES existCreateRemoteThread 说文件不存在,但它确实存在
【发布时间】:2014-06-21 13:53:26
【问题描述】:

我正在尝试使用 Interop 将 .dll 注入另一个进程的内存。

这是我的 C# 代码:

class Program
{
        static void Main(string[] args)
        {
            var result = Inject(Process.GetProcessesByName("notepad")[0].Id);

            Console.WriteLine(result);

            if (result < 0)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            Console.ReadLine();
        }

        [DllImport("Testing.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int Inject(int dwProcessId);
}

函数Inject的代码是这样的(注意return -6上的注释):

//C++ .dll that does actually exists
const char* DLL_NAME = "C:\\Users\\Bruno\\Source\\Repos\\CourseGuidance\\InteropTesting\Debug\\Loader.dll";

TESTING_API DWORD Inject(DWORD dwProcessId)
{
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);

    if (hProcess == NULL)
        return -1;

    HMODULE hModule = GetModuleHandleW(L"kernel32.dll");

    if (hModule == NULL)
        return -2;

    FARPROC pLoadLibrary = GetProcAddress(hModule, "LoadLibraryA");

    if (pLoadLibrary == NULL)
        return -3;

    LPVOID pMemory = VirtualAllocEx(hProcess, NULL, strlen(DLL_NAME) + 1, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);

    if (pMemory == NULL)
        return -4;

    BOOL result = WriteProcessMemory(hProcess, pMemory, DLL_NAME, strlen(DLL_NAME) + 1, NULL);

    if (!result)
        return -5;

    HANDLE hThread = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE) pLoadLibrary, pMemory, 0, NULL);

    if (hThread == NULL)
        return -6;

    WaitForSingleObject(hThread, INFINITE);

    VirtualFreeEx(hProcess, pMemory, strlen(DLL_NAME) + 1, MEM_RELEASE);

    CloseHandle(hThread);

    CloseHandle(hProcess);

    return 0;
}

我认为我得到的错误可能具有误导性,因为该文件确实存在于该文件夹中。我还认为错误可能是因为LoadLibraryA,它是用于ASCII,甚至尝试使用LoadLibraryW,但我仍然遇到同样的问题。

如果有人知道可能出了什么问题,你能给我提供正确的方向吗?

【问题讨论】:

  • 实际错误是什么?十六进制错误代码?会不会是依赖问题,DLL依赖于其他找不到的模块?
  • 实际代码为2
  • 你有一个标准的一对一错误,在 C 字符串中很常见。您忘记复制 0 终止符。请改用strlen(DLL_NAME) + 1
  • 在您的 const char* DLL_NAME 中,其中一个反斜杠没有加倍。
  • 您为什么不告诉我们 Inject 函数返回什么值?

标签: c# visual-c++ dll-injection createremotethread


【解决方案1】:

您没有将Inject 声明为SetLastError=true。因此,你从Marshal.GetLastWin32Error 得到的值是垃圾:

Marshal.GetLastWin32Error Method

返回最后一个非托管函数返回的错误代码 使用平台调用 调用,该调用具有 DllImportAttribute.SetLastError 标志设置

只有在应用 System.Runtime.InteropServices.DllImportAttribute 到方法 签名并将 SetLastError 字段设置为 true。这个过程 因使用的源语言而异:C# 和 C++ 为 false 默认情况下,但 Visual Basic 中的 Declare 语句为真。

【讨论】:

    最近更新 更多