I want to know what are the files opened/access by a process. May i know how to do that? I tried to use Deviare, a free hooking api to help me, but was unable to find any useful information from their AIP lib or forum.
I only know i have to hook on to kernel32.dll and createFileW and i am not sure of how to continue.
Pls help me. Thanks in advance.
It's right. You have to hook the function CreateFileA/W in kernel32.dll to monitor the acces. Do you want to hook these APIs in your own process or in an other process?
If you want to hook functions in your own process you can use
void *DetourFunc(BYTE *src, const BYTE *dst, const int len)
{
BYTE *jmp = (BYTE*)malloc(5+len);
DWORD dwback;
VirtualProtect(src,len,PAGE_READWRITE,&dwback);
memcpy(jmp,src,len);
jmp += len;
jmp[0] = 0xE9;
*(DWORD*)(jmp+1) = (DWORD)(src+len - jmp) - 5;
src[0] = 0xE9;
*(DWORD*)(src+1) = (DWORD)(dst - src) - 5;
VirtualProtect(src,len,dwback,&dwback);
return (jmp-len);
}
for it. These function detours the function src (f.e. MessageBoxA()) to function dst. As len you can use 5. It returns a function pointer to the original function.
An example call:
typedef int (WINAPI *__MessageBox)(
__in_opt HWND hWnd,
__in_opt LPCTSTR lpText,
__in_opt LPCTSTR lpCaption,
__in UINT uType
);
__MessageBox _MessageBox;
int cMessageBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
{
//here you can change anything you want
return _MessageBox(hWnd,lpText,lpCaption,uType);
}
int main(void)
{
BYTE *hookfunc = (BYTE*)GetProcAddress(LoadLibrary("user32.dll"),"MessageBoxA");
_MessageBox = (__MessageBox)DetourFunc(hookfunc,(BYTE*)cMessageBox,5);
return 0;
}
That's an usermode hook. If you want to do this systemwide I would use a device driver. Here is a tutorial about this. http://www.codeproject.com/KB/system/driverdev.aspx
And if you are using VC++ compile in multibyte mode ;).
If you want to hook in an other process just google DLL-Injection ;).
Related
Trying to hook to the Present call in Dx12/Dxgi. Is not possible to get the function address via GetProcAddress and some people already figured it out how to obtain the offset directly.
Using Minhook/Kiero (https://github.com/Rebzzel/kiero) it works correctly, say:
typedef HRESULT(APIENTRY* Present12) (IDXGISwapChain* pSwapChain, UINT SyncInterval, UINT Flags);
static Present12 oPresent = NULL;
HRESULT APIENTRY ownPresent(IDXGISwapChain* pSwapChain, UINT SyncInterval, UINT Flags)
{
return oPresent(pSwapChain,SyncInterval, Flags);
}
// On the actual hook part:
void* target = (void*)g_methodsTable[_index];
MH_CreateHook(target, _function, _original);
MH_EnableHook(target);
// Where target is the pointer to the offset where the actual function is located
// _function is the detour function, my ownPresent
// _original will be pointing to the original function
This works as expected, from my own Present:
HRESULT APIENTRY ownPresent(IDXGISwapChain* pSwapChain, UINT SyncInterval, UINT Flags)
{
return oPresent(pSwapChain,SyncInterval, Flags);
}
All good, the original Present is called at the end.
However, tried to migrate this to Detours and the comparable code would be:
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
void* target = (void*)g_methodsTable[_index];
DetourAttach(&(PVOID&)target, _function);
if (_original)
{
*_original = target;
}
DetourTransactionCommit();
It works in the sense that the detour function is being called, however, seems that now the target pointer has the code modified to perform the jump, because now ownPresent calls to ownPresent again, it's recursive.
Not sure if Detours stores a copy of the original code the same way MinHook does, so I can point to the original function and avoid this recursive behavior.
Please let me know if I am using detours incorrectly. Not really sure how to proceed.
Thanks in advance!
How can i achieve this what i wrote in topic? I have access to win32-api in my node app and i know this window processID which i want to change. I know that functions EnumWindows() and GetWindowThreadProcessId() would be usefull in this but i dont know even what to pass as parameters to EnumWindows() and what this function will return.
First you need to make sure your window is top-level when using EnumWindows.
The function has 2 parameters:
lpEnumFunc
Type: WNDENUMPROC
A pointer to an application-defined callback function. For more
information, see EnumWindowsProc.
lParam
Type: LPARAM
An application-defined value to be passed to the callback function.(you can pass the process id to it)
You could call the GetWindowThreadProcessId in the callback EnumWindowsProc and compare with the process id for each window found.
Here is the sample in C++:
#include <windows.h>
#include <iostream>
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
DWORD *pid = (DWORD*)(lParam);
DWORD processId;
if (GetWindowThreadProcessId(hwnd, &processId) && processId == *pid)
{
WCHAR Title[MAX_PATH] = { 0 };
GetWindowTextW(hwnd,Title, MAX_PATH);
wprintf(L"Title : %s\n", Title);
SetWindowTextW(hwnd, L"TestTitle");
return FALSE; //end enumerating;
}
// Continue enumerating
return TRUE;
}
int wmain(int argc, wchar_t* argv[])
{
DWORD pid = 11244;//set the process id you have.
BOOL bResult = EnumWindows(EnumWindowsProc,(LPARAM)&pid);
return 0;
}
And for using EnumWindowsProc callback in node.js, you could refer to this sample .
in the exe project:
int WINAPI WinMain( __in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in_opt LPSTR lpCmdLine, __in int nShowCmd )
{
g_hMainWnd=CreateDialog(hInstance,MAKEINTRESOURCE(IDD_DIALOG1),NULL,(DLGPROC)DialogProc);
RECT rcWnd;
GetWindowRect(g_hMainWnd,&rcWnd);
int X=(GetSystemMetrics(SM_CXSCREEN)-rcWnd.right+rcWnd.left)>>1,
Y=(GetSystemMetrics(SM_CYSCREEN)-rcWnd.bottom+rcWnd.top)>>1;
MoveWindow(g_hMainWnd,X,Y,rcWnd.right-rcWnd.left,rcWnd.bottom-rcWnd.top,FALSE);
ShowWindow(g_hMainWnd,SW_SHOW);
BOOL bRet;
MSG msg;
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
MessageBox(NULL,_T("GetMessage error with -1 returned!"),_T("error"),MB_ICONHAND);
break;
}
else if (!IsWindow(g_hMainWnd) || !IsDialogMessage(g_hMainWnd, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
I changed the project setting to output a dll firstly.
Then I changed the WinMain to:
BOOL APIENTRY DllMain( __in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in_opt LPSTR lpCmdLine, __in int nShowCmd )
{
g_hMainWnd=CreateDialog(hInstance,MAKEINTRESOURCE(IDD_DIALOG1),NULL,(DLGPROC)DialogProc);
HWND hMainWnd;
//DialogProc involves the critical initialization of the data required for the export function used later
return 0;
}
So, if it is a foolish idea, or have I missed something?
Thank you all!
BOOL WINAPI DllMain(
HINSTANCE hinstDLL, // handle to DLL module
DWORD fdwReason, // reason for calling function
LPVOID lpReserved ) // reserved
{
// Perform actions based on the reason for calling.
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
// Initialize once for each new process.
// Return FALSE to fail DLL load.
break;
case DLL_THREAD_ATTACH:
// Do thread-specific initialization.
break;
case DLL_THREAD_DETACH:
// Do thread-specific cleanup.
break;
case DLL_PROCESS_DETACH:
// Perform any necessary cleanup.
break;
}
return TRUE; // Successful DLL_PROCESS_ATTACH.
}
For more informations: Dll entry point
The definition of DllMain is to be used by the operating system, and on a few occasions you must enter their codes. To execute the code that implements your EXE, you must create a public routine that receives the required parameters.
Use Visual Studio do create one library project to export some data and functions.
New Project-> Select Viasual c++ -> Select Win32 -> Win32 Project -> Name your project -> Next -> Select DLL -> Select Export symbols -> finish
The final project will contain a variable being exported and a public routine. Use as a template in your code.
I try to create a managed C++ assembly in VS 2010 to interface with WinAPI and use it in my other C# assemblies. I've read all posts, even searched in code in GitHub, with no success.
Maybe its about the __clrcall in the error message, should not it be __stdcall? Any ideas?
The exact error message is:
error C2440: '=' : cannot convert from 'LRESULT (__clrcall xxx::Win32Demo::* )(HWND,UINT,WPARAM,LPARAM)' to 'WNDPROC'
The source code:
#pragma once
using namespace System;
using namespace System::Drawing;
#include "stdafx.h"
#include "windows.h"
namespace xxx
{
ref class Win32Demo
{
private: HWND__ * handle;
private: static Char * windowClass;
public:
Win32Demo(void)
{
}
static Win32Demo()
{
tagWNDCLASSEXW w;
windowClass = (wchar_t*) L"Hello";
w.cbSize = sizeof(tagWNDCLASSEXW);
w.style = 0x803;
w.lpfnWndProc = WindowProc; // Error
w.cbClsExtra = 0;
w.cbWndExtra = 0;
w.hInstance = 0;
w.hIcon = 0;
w.hCursor = 0;
w.hbrBackground = CreateSolidBrush(0);
w.lpszMenuName = NULL;
w.lpszClassName = windowClass;
w.hIconSm = 0;
}
public :
static LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
return 0;
}
};
}
This goes wrong because your WndProc() function is being compiled to IL, not machine code. Which happened because you compile it with /clr in effect. It is not just a compile time error, it also cannot work at runtime. Windows doesn't know how to call a managed method, not without the kind of help you get from Marshal::GetFunctionPointerForDelegate().
It is better to just not go there. Either move this code in a separate .cpp file that you compile without the /clr option. Or use #pragma managed(push, off) before this code so that it gets compiled to machine code instead of IL.
And consider the managed class wrappers that give you the same kind of functionality. Like the classes in the System.Windows.Forms namespace. Or if you want to keep this code then derive your own class from the NativeWindow class to attach the window handle, allowing you to override WndProc() with managed code.
Apparently the __stdcall calling convention is not supported for methods of managed classes. So you'll need to put WindowProc inside an unmanaged class:
class WindowProcCallback
{
public:
static LRESULT __stdcall WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
...
}
};
ref class Win32Demo
{
...
};
One suggestion: turn on warnings so that you get warnings about stuff like this. With warnings you would have gotten the following warning:
warning C4441: calling convention of '__stdcall ' ignored; '__clrcall ' used instead
We are hooking TextOut(),ExtTextOut() and DrawText() methods GLOBALLY .
i.e.
hhook = SetWindowsHookEx(WH_CBT, function_address, module_handle, 0);
But we want to hook/unhook only a particular exe. Can someone tell us how to check all the existing threads and get the required exe and hook/unhook only that.
Please provide help.
Thank you
You can enumerate the processes using the PSAPI specifically EnumProcesses
You'll need to #include "psapi.h" from the SDK and add PSAPI.lib to the linker inputs.
Ex:
DWORD aiPID[1000], iCb=1000;
DWORD iCbneeded = 0;
if (!EnumProcesses(aiPID, iCb, &iCbneeded)) return(E_FAIL);
int iNumProc=iCbneeded/sizeof(DWORD);
for(int i=0; i < iNumProc; i++)
{
// First, get a handle to the process
HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, aiPID[i]);
if (!hProc) continue;
TCHAR szName[MAX_PATH] = _T("<unknown>");
HINSTANCE hMod = NULL;
if (EnumProcessModules(hProc, &hMod, sizeof(hMod), &iCbneeded))
{
GetModuleFileNameEx(hProc, hMod, (LPTSTR)szName, MAX_PATH);
}
CloseHandle(hProc);
}
Edit: Sorry - That only gives you the lists of processes... to get the threads for each see ListProcessThreads passing in the PID for each enumerated process.