将LPVOID强制转换为结构

本文关键字:结构 转换 LPVOID | 更新日期: 2023-09-27 18:26:20

我想读取通过CreateRemoteThread发送到另一个进程中注入的DLL的参数。

我可以毫无问题地调用该函数,只是不知道如何将LPVOID强制转换为结构。

这是一个例子:

#pragma pack(push,1)
struct tagRemoteThreadParams
{
    int Param1;
    int Param2;
} RemoteThreadParams, *PRemoteThreadParams;
#pragma pack(pop)
DWORD WINAPI testfunction(LPVOID param)
{
    // cast LPVOID to tagRemoteThreadParams (param)
    WriteToLog("YES YOU CALLED THE FUNCTION WITH PARAM: ");
    return 0;
}

这是我的结构,以及我如何在进程中分配内存:

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct RemoteThreadParams
{
    [MarshalAs(UnmanagedType.I4)]
    public int Param1;
    [MarshalAs(UnmanagedType.I4)]
    public int Param2;
}
public uint CallFunction(int _arg1)
{
    RemoteThreadParams arguments = new RemoteThreadParams();
    arguments.Param1 = 1;
    arguments.Param2 = 2;
    //pointer to the function im trying to call
    IntPtr _functionPtr = IntPtr.Add(this.modulePtr, 69772);
    // Allocate some native heap memory in your process big enough to store the
    // parameter data
    IntPtr iptrtoparams = Marshal.AllocHGlobal(Marshal.SizeOf(arguments));
    // Copies the data in your structure into the native heap memory just allocated
    Marshal.StructureToPtr(arguments, iptrtoparams, false);
    //allocate som mem in remote process
    IntPtr lpAddress = VirtualAllocEx(this.processHandle, IntPtr.Zero, (IntPtr)Marshal.SizeOf(arguments), AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite);
    if (lpAddress == IntPtr.Zero)
    {
        return 0;
    }
    if (WriteProcessMemory(this.processHandle, lpAddress, iptrtoparams, (uint)Marshal.SizeOf(arguments), 0) == 0)
    {
        return 0;
    }
    //Free up memory
    Marshal.FreeHGlobal(iptrtoparams);
    uint threadID = 0;
    IntPtr hThread = CreateRemoteThread(this.processHandle, IntPtr.Zero, 0, _functionPtr, lpAddress, 0, out threadID);
    if (hThread == IntPtr.Zero)
    {
        //throw new ApplicationException(Marshal.GetLastWin32Error().ToString());
        throw new Win32Exception();
    }
    WaitForSingleObject(hThread, 0xFFFFFFFF);
    // wait for thread to exit

    // get the thread exit code
    uint exitCode = 0;
    GetExitCodeThread(hThread, out exitCode);
    // close thread handle
    CloseHandle(hThread);
    return exitCode;
}

将LPVOID强制转换为结构

如果我正确理解您的代码,您可以将UT8编码的字符串注入对方的进程内存(我有点惊讶它能工作)。

假设它确实有效,那么在C++代码中,您需要将param指向的UTF8编码字节数组转换为C++能够理解的某种字符串。

一种方法是使用MultiByteToWideChar

另一种方法是使用STL。我在这里发现了一个问题。

铸造问题的答案是:

struct tagRemoteThreadParams *tData = (struct tagRemoteThreadParams *)param;

感谢大家的帮助