Windows Cmd Hook not working - cmd

i am trying to hook the CreateProcess under cmd.exe.
i manage to inject the dll the the cmd process but after the injection the dll process detach message receive and i fail to hook the createprocess function call.
i am using easyhook.
my code:
#include <windows.h>
#include <Shlwapi.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#include <easyhook.h>
BOOL WINAPI myCreateProcess(
_In_opt_ LPCTSTR lpApplicationName,
_Inout_opt_ LPTSTR lpCommandLine,
_In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes,
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ BOOL bInheritHandles,
_In_ DWORD dwCreationFlags,
_In_opt_ LPVOID lpEnvironment,
_In_opt_ LPCTSTR lpCurrentDirectory,
_In_ LPSTARTUPINFO lpStartupInfo,
_Out_ LPPROCESS_INFORMATION lpProcessInformation
){
OutputDebugString(L"\n !!!!!! In CreateProcess HOOK\n !!!!!!!!");
return CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCommandLine, lpStartupInfo, lpProcessInformation);
}
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
BOOL bErrorFlag = FALSE;
DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
DWORD dwBytesWritten = 0;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
HOOK_TRACE_INFO hHook = { NULL }; // keep track of our hook
// Install the hook
NTSTATUS result = LhInstallHook(
GetProcAddress(GetModuleHandle(TEXT("kernel32")), "CreateProcessW"),
myCreateProcess,
NULL,
&hHook);
if (FAILED(result))
{
OutputDebugString(L"!!!!!!!!!!!FAIL!!!!!!!!");
return 1;
}
ULONG ACLEntries[1] = { 0 };
LhSetInclusiveACL(ACLEntries, 1, &hHook);
OutputDebugString(L"!!!!!!!!!!!!Injection Succeed!!!!!!!!!!!!");
break;
}
case DLL_THREAD_ATTACH:{
OutputDebugString(L"!!!!!!!!!!!!dll thread attach!!!!!!!!!!!!");
break;
}
case DLL_THREAD_DETACH:
{
OutputDebugString(L"!!!!!!!!!!!!dll thread Detach!!!!!!!!!!!!");
break;
}
case DLL_PROCESS_DETACH:
{
OutputDebugString(L"!!!!!!!!!!!!dll process Detach!!!!!!!!!!!!");
break;
}
}
}
i receive the "Injection Succeed" message and right after the "dll process Detach" message .
any ideas?

try changing :
LhSetInclusiveACL(ACLEntries, 1, &hHook);
to :
LhSetExclusiveACL(ACLEntries, 1, &hHook);

Related

Is it possible to subclass a web browser using winapi c++?

The main goal is to block maximalize web browser window using subclassing and dll.
I have 2 apps: injector and the dll.
In injector app I load that dll, find window by title, get functions from dll and execute that functions ( their names are hook and unhook ) from dll. So this is standard injector. Of course I check is something NULL and I don't get any errors.
In dll I have 5 functions:
dllMain (here I only set global hInstance variable, which is in shared memory ):
BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
{
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
{
if (hInstance == NULL)
{
hInstance = hinstDLL;
}
break;
}
...
}
return TRUE;
}
Hook ( HandleofTarget is the HWND, which I get from FindWindow ; I use this function in injector ):
extern "C" __declspec(dllexport) bool hook( HWND HandleofTarget)
{
hTarget=HandleofTarget;
hhook=SetWindowsHookEx(WH_CBT,cbtHookProc,hInstance, GetWindowThreadProcessId(hTarget,NULL));
if(hhook==NULL)
return 0;
else
return 1;
}
Unhook ( here I unhook hooks - I use this function in injector):
extern "C" __declspec(dllexport) void unhook(void)
{
if(hhook != NULL)
UnhookWindowsHookEx( hhook );
}
cbtHookProc ( hook callback, where I change window procedure ):
LRESULT CALLBACK cbtHookProc( int code, WPARAM wParam, LPARAM lParam )
{
if( code < 0 ) return CallNextHookEx( 0, code, wParam, lParam );
if (code == HCBT_ACTIVATE)
{
if((HWND)(wParam)==hTarget)
{
if(done == FALSE)
{
g_OldWndProc =(WNDPROC)(SetWindowLongPtr ( (HWND)(wParam), GWLP_WNDPROC,reinterpret_cast<LONG_PTR>( NewWndProc )));
done = TRUE;
}
}
}
return CallNextHookEx( 0, code, wParam, lParam );
}
NewWndProc ( new Window procedure, where I would like to block maximalize ):
LRESULT CALLBACK NewWndProc( HWND hwnd, UINT mesg, WPARAM wParam, LPARAM lParam )
{
switch( mesg )
{
case WM_SYSCOMMAND:
{
if(wParam == SC_MAXIMIZE)
{
return 1;
}
}
break;
}
return CallWindowProc( g_OldWndProc, hwnd, mesg, wParam, lParam );
}
When I test this dll with other apps - it works. When I use this dll with web browser like Internet Edge and Google Chrome - it doesn't works. That web browser, which I try injected works slower, but I can still maximalize that window. When I debuq dll, in web browser after SetWindowsHookEx I see that hook is not NULL, but my code doesn't go to cbtHookProc. What is going on with web browser?
UPDATE:
One more time - thank you Strive Sun - MSFT for helping me.
I change the lines in cbtHookProc, but it still doesn't work. My cbtHookProc is don't called by webBrowser - that is problem.
When I looked at your gif I see something what I don't have and I think that is the problem. My injector app looks like this:
hDll = LoadLibrary( L"dllka10" );
hHookedWindow=FindWindow(TEXT("Chrome_WidgetWin_1"),TEXT("Nowa karta - Google Chrome"));
if( hDll && hHookedWindow)
{
qDebug()<<"hDll and hHookedWindow are not NULL!";
funHook =( MYPROC2 ) GetProcAddress( hDll, (LPCSTR) "hook" );
funUnhook = ( MYPROC ) GetProcAddress( hDll, (LPCSTR) "unhook" );
if( funHook )
{
qDebug()<<funHook(hHookedWindow);
}
}
I don't use CreateThread(). Is it important here?
UPDATED 2
LRESULT CALLBACK cbtHookProc( int code, WPARAM wParam, LPARAM lParam )
{
if( code < 0 ) return CallNextHookEx( 0, code, wParam, lParam );
std::fstream file;
file.open("C:\\Users\\tom\\Desktop\\logs.txt",std::ios::out|std::ios::app);
file<<"In cbtHook function!"<<std::endl;
file.close();
if (code == HCBT_MINMAX)
{
if (LOWORD(lParam) == SW_SHOWMAXIMIZED)
{
return 1;
}
}
return CallNextHookEx( 0, code, wParam, lParam );
}
When I run chrome application - my logs.txt is empty. When I run other app - I have logs.
UPDATED 3
In my dll I have:
#ifdef __GNUC__
HWND hTarget __attribute__((section (".shared"), shared)) =NULL;
HWND hApp __attribute__((section (".shared"), shared)) = NULL;
bool done __attribute__((section (".shared"), shared)) =FALSE;
HINSTANCE hInstance __attribute__((section (".shared"), shared)) =NULL;
HHOOK hhook __attribute__((section (".shared"), shared)) = NULL;
WNDPROC g_OldWndProc __attribute__((section (".shared"), shared)) = NULL;
#endif
#ifdef _MSC_VER
#pragma data_seg(".shared")
HWND hTarget=NULL;
HWND hApp = NULL;
bool done=FALSE;
HINSTANCE hInstance=NULL;
HHOOK hhook = NULL;
WNDPROC g_OldWndProc = NULL;
#pragma data_seg()
#pragma comment(linker, "/section:.shared,RWS")
#endif
in my injector I don't have any pragma - I have only ( QT ):
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <iostream>
#include "string.h"
#include "windows.h"
I can't reproduce your problem, but you can try another easier method.
HCBT_MINMAX : Specifies, in the low-order word, a show-window value
(SW_) specifying the operation. For a list of show-window values, see
the ShowWindow. The high-order word is undefined.
if (code == HCBT_MINMAX)
{
if (LOWORD(lParam) == SW_SHOWMAXIMIZED)
{
return 1;
}
}
No need to use HCBT_ACTIVATE to obtain window handles and compare their handles.
Updated:
Code works fine.
My code sample:
DLL:
// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include "stdio.h"
#include <windows.h>
HHOOK hCBT = NULL;
HWND hTarget;
HMODULE thisModule;
LRESULT CALLBACK _cbtProc(int code, WPARAM wParam, LPARAM lParam)
{
if (code < 0) return CallNextHookEx(0, code, wParam, lParam);
if (code == HCBT_MINMAX)
{
if (LOWORD(lParam) == SW_SHOWMAXIMIZED)
{
return 1;
}
}
return CallNextHookEx(0, code, wParam, lParam);
}
#ifdef __cplusplus //If used by C++ code.
extern "C" { //we need to export the C interface
#endif
__declspec(dllexport) BOOL WINAPI InstallHooks(HWND HandleofTarget)
{
hTarget = HandleofTarget;
DWORD tid = GetWindowThreadProcessId(hTarget, NULL);
hCBT = SetWindowsHookEx(WH_CBT, _cbtProc, thisModule, tid);
return (hCBT) ? TRUE : FALSE;
}
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus //If used by C++ code.
extern "C" { //we need to export the C interface
#endif
__declspec(dllexport) void WINAPI RemoveHooks()
{
UnhookWindowsHookEx(hCBT);
MessageBox(NULL, L"unhook", L" ", MB_OK);
hCBT = NULL;
}
#ifdef __cplusplus
}
#endif
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
thisModule = hModule;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
main.cpp
#include <Windows.h>
#include <stdio.h>
#include <psapi.h>
#include <shlwapi.h>
#include <tchar.h>
#pragma comment(lib,"Kernel32.lib")
#pragma comment(lib,"shlwapi.lib")
#pragma comment(linker, "/SECTION:.shared,RWS")
using namespace std;
HINSTANCE hinstDLL;
typedef void (*RemoveHooks)();
DWORD __stdcall CreateThreadFunc(LPVOID)
{
while (1)
{
if (GetAsyncKeyState(0x50) & 0x0001)
{
RemoveHooks removeHooks = (RemoveHooks)GetProcAddress(hinstDLL, "RemoveHooks");
removeHooks();
}
}
return 0;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == WM_DESTROY) {
PostQuitMessage(0);
}
return DefWindowProc(hwnd, message, wParam, lParam);
};
int main()
{
HWND hwnd = FindWindow(L"Chrome_WidgetWin_1", L"Google Translate - Google Chrome");
CreateThread(NULL, 0, CreateThreadFunc, 0, 0, 0);
hinstDLL = LoadLibrary(TEXT("D:\\Start from 11.2\\WM_CBT_DLL\\x64\\Debug\\WM_CBT_DLL.dll"));
BOOL(*InstallHooks)(HWND);
InstallHooks = (BOOL(*)(HWND)) GetProcAddress(hinstDLL, "InstallHooks");
BOOL l = InstallHooks(hwnd);
int err = GetLastError();
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

DllMain not called in cygwin-gcc compiled program

I'm trying to build a DLL with cygwin, but from DbgView, no output is observed:
#include <windows.h>
__declspec(dllexport) BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
OutputDebugStringA("DLL_PROCESS_ATTACH called");
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
__attribute__((stdcall))
int _DllMainCRTStartup(int handle, int reason, void *ptr)
{
return DllMain(handle, reason, ptr);
}
So far it looks like DllMain is not called at all, what was wrong?

Getting error 127 when calling GetProcAddress

I am writing a global hook for WH_GETMESSAGE. But I am getting the error code 127 i.e.,ERROR_PROC_NOT_FOUND, when calling the GetProcAddress function from the dll. Its unable to find the GetMsgProc. Any idea why?
Also, I am new to this kind of programming, so apologies for any mistake that's not expected.
DLL File:
#include "windows.h"
#include <stdio.h>
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
return TRUE;
}
__declspec(dllexport) LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
MessageBox(NULL, TEXT("I am in"),TEXT("In a DLL"), MB_OK);
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
Program Loading the DLL file:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
typedef LRESULT(CALLBACK *LPGetMsgProc)(int nCode, WPARAM wParam, LPARAM lParam);
int main()
{
HMODULE hDll = LoadLibrary(_T("../../dllTouchInputHook/x64/Debug/dllTouchInputHook.dll"));
LPGetMsgProc proc = (LPGetMsgProc)GetProcAddress(hDll, "GetMsgProc");
if (proc == NULL) {
printf("The error code is %d", GetLastError());
}
HHOOK hMsgHook = SetWindowsHookEx(WH_GETMESSAGE, proc, hDll, 0);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(hMsgHook);
return 0;
}
The function is not being found because it is not being exported as "GetMsgProc" like you are expecting. It is actually being exported more like "_GetMsgProc#12" (32bit) or "_GetMsgProc#20" (64bit) instead. If you want it exported as "GetMsgProc" then you need to use a .DEF file when compiling the DLL.
You shouldn't be implementing the hook in this manner to begin with. You should move the call to SetWindowsHookEx() inside the DLL itself, and then export a function to call it, eg:
#include "windows.h"
#include <stdio.h>
HINSTANCE hThisDLL;
HHOOK hMsgHook;
BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
hThisDLL = hinstDLL;
return TRUE;
}
LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
MessageBox(NULL, TEXT("I am in"), TEXT("In a DLL"), MB_OK);
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
__declspec(dllexport) BOOL WINAPI InstallHook()
{
if (!hMsgHook)
hMsgHook = SetWindowsHookEx(WH_GETMESSAGE, &GetMsgProc, hThisDll, 0);
return (hMsgHook != NULL);
}
__declspec(dllexport) VOID WINAPI UninstallHook()
{
if (hMsgHook)
{
UnhookWindowsHookEx(hMsgHook);
hMsgHook = NULL;
}
}
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
typedef BOOL (WINAPI *LPInstallHook)();
typedef VOID (WINAPI *LPUninstallHook)();
int main()
{
HMODULE hDll = LoadLibrary(_T("../../dllTouchInputHook/x64/Debug/dllTouchInputHook.dll"));
if (!hDll)
{
printf("The error code is %d", GetLastError());
return -1;
}
LPInstallHook installProc = (LPInstallHook) GetProcAddress(hDll, "InstallHook"); // or "_InstallHook"
LPUninstallHook uninstallProc = (installProc) ? (LPUninstallHook) GetProcAddress(hDll, "UninstallHook") : NULL; // or "_UninstallHook"
if (!(installProc && uninstallProc))
{
printf("The error code is %d", GetLastError());
FreeLibrary(hDll);
return -1;
}
if (!installProc())
{
printf("The error code is %d", GetLastError());
FreeLibrary(hDll);
return -1;
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
uninstallProc();
FreeLibrary(hDll);
return 0;
}

Windows driver : PreOperationCallback not called

I'm trying to create a basic minifilter driver using Microsoft examples (PassThough, minispy...), but my MfPreOperationCallback is not called. I tried different contexts (even if I'm not sure to understand how that works...). I tried the PassThrough example and it works very well and it is very similar to my code...
Here is my inf file and my code :
;
; KmdfMiniFilter.inf
;
[Version]
Signature = "$WINDOWS NT$"
Class = "ActivityMonitor"
ClassGuid = {b86dff51-a31e-4bac-b3cf-e8cfe75c9fc2}
Provider = %ProviderString%
DriverVer = 02/09/2017,1.0.0.0
CatalogFile = KmdfMiniFilter.cat
[DestinationDirs]
DefaultDestDir = 12
KmdfMiniFilter.DriverFiles = 12
[DefaultInstall]
OptionDesc = %ServiceDescription%
CopyFiles = KmdfMiniFilter.DriverFiles
[DefaultInstall.Services]
AddService = %ServiceName%,,KmdfMiniFilter.Service
[DefaultUninstall]
DelFiles = KmdfMiniFilter.DriverFiles
[DefaultUninstall.Services]
DelService = %ServiceName%,0x200
[KmdfMiniFilter.Service]
DisplayName = %ServiceName%
Description = %ServiceDescription%
ServiceBinary = %12%\%DriverName%.sys
Dependencies = "FltMgr"
ServiceType = 2 ; SERVICE_FILE_SYSTEM_DRIVER
StartType = 3 ; SERVICE_DEMAND_START
ErrorControl = 1 ; SERVICE_ERROR_NORMAL
LoadOrderGroup = "FSFilter Activity Monitor"
AddReg = KmdfMiniFilter.AddRegistry
[KmdfMiniFilter.AddRegistry]
HKR,,"DebugFlags",0x00010001 ,0x0
HKR,,"SupportedFeatures",0x00010001,0x3
HKR,"Instances","DefaultInstance",0x00000000,%DefaultInstance%
HKR,"Instances\"%Instance1.Name%,"Altitude",0x00000000,%Instance1.Altitude%
HKR,"Instances\"%Instance1.Name%,"Flags",0x00010001,%Instance1.Flags%
[KmdfMiniFilter.DriverFiles]
%DriverName%.sys
[SourceDisksFiles]
KmdfMiniFilter.sys = 1,,
[SourceDisksNames]
1 = %DiskId1%,,,
[Strings]
ProviderString = "GUIDONO"
ServiceDescription = "KmdfMiniFilter mini-filter driver"
ServiceName = "KmdfMiniFilter"
DriverName = "KmdfMiniFilter"
DiskId1 = "File Change Monitoring Device Installation Disk"
DefaultInstance = "KmdfMiniFilter Instance"
Instance1.Name = "KmdfMiniFilter Middle Instance"
Instance1.Altitude = "370000"
Instance1.Flags = 0x1 ; Suppress automatic attachments
Registration.c
/**
Filter registration information
*/
#pragma once
#include <fltKernel.h>
#include "MiniFilter.h"
// Callbacks : list of FLT_OPERATION_REGISTRATION structures, one for each type of I/O for which the minifilter
// registers preoperation and postoperation callback routines.
// The last element must be IRP_MJ_OPERATION_END
CONST FLT_OPERATION_REGISTRATION Callbacks[] =
{
{
IRP_MJ_CREATE,
0,
MfPreOperationCallback,
MfPostOperationCallback
},
{ IRP_MJ_OPERATION_END }
};
// Defines the minifilter context structure
typedef struct _MINIFILTER_TRANSACTION_CONTEXT {
ULONG Flags;
ULONG Count;
} MINIFILTER_TRANSACTION_CONTEXT, *PMINIFILTER_CONTEXT;
// Contexts : a context structure is used to register context types
const FLT_CONTEXT_REGISTRATION Contexts[] =
{
{
FLT_TRANSACTION_CONTEXT, // Context type
0, // Flags
MfDeleteTxfContext, // ContextCleanupCallback
sizeof(MINIFILTER_TRANSACTION_CONTEXT), // Size
'ypsM' // PoolTag
},
{
FLT_CONTEXT_END
}
};
// This defines what we want to filter with FltMgr
CONST FLT_REGISTRATION FilterRegistration =
{
sizeof(FLT_REGISTRATION), // Size
FLT_REGISTRATION_VERSION, // Version
0, // Flags
Contexts, // Contexts
Callbacks, // Callbacks
MfUnload, // FilterUnload
MfInstanceSetup, // InstanceSetup
MfInstanceQueryTeardown, // InstanceQueryTeardown
MfInstanceTeardownStart, // InstanceTeardownStart
MfInstanceTeardownComplete, // InstanceTeardownComplete
NULL, // GenerateFileName
NULL, // GenerateDestinationFileName
NULL, // NormalizeNameComponent
};
Driver.c
#include <ntifs.h>
#include <wdf.h>
#include "RegistrationData.h"
#include "MiniFilter.h"
// Global data
MINIFILTER_DATA MfData;
DRIVER_INITIALIZE DriverEntry;
NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath)
{
UNREFERENCED_PARAMETER(RegistryPath);
//DbgSetDebugFilterState(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, TRUE);
NTSTATUS status;
MfData.Driver = DriverObject;
// Registering the minifilter driver
status = FltRegisterFilter(DriverObject, &FilterRegistration, &MfData.Filter);
KdPrint(("MINIFILTER INIT\n"));
if (!NT_SUCCESS(status)) {
KdPrint(("MINIFILTER ERROR : FltRegisterFilter failed. Code 0x%x\n", status));
return STATUS_UNSUCCESSFUL;
}
status = FltStartFiltering(MfData.Filter);
if (!NT_SUCCESS(status)) {
KdPrint(("MINIFILTER ERROR : FltStartFiltering faild. Code 0x%x\n", status));
FltUnregisterFilter(MfData.Filter);
return STATUS_UNSUCCESSFUL;
}
KdPrint(("MINIFILTER is Filtering!\n"));
return status;
}
NTSTATUS MfUnload(_In_ FLT_FILTER_UNLOAD_FLAGS Flags)
{
UNREFERENCED_PARAMETER(Flags);
PAGED_CODE();
KdPrint(("MINIFILTER UNLOAD\n"));
FltUnregisterFilter(MfData.Filter);
return STATUS_SUCCESS;
}
NTSTATUS MfQueryTearDown(_In_ PCFLT_RELATED_OBJECTS FltObjects, _In_ FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags)
{
UNREFERENCED_PARAMETER(FltObjects);
UNREFERENCED_PARAMETER(Flags);
PAGED_CODE();
return STATUS_SUCCESS;
}
MiniFilter.h
#pragma once
#include <fltKernel.h>
typedef struct MINIFILTER_DATA {
PDRIVER_OBJECT Driver;
PFLT_FILTER Filter;
} MINIFILTER_DATA;
FLT_PREOP_CALLBACK_STATUS MfPreOperationCallback(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
);
FLT_POSTOP_CALLBACK_STATUS MfPostOperationCallback(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ PVOID CompletionContext,
_In_ FLT_POST_OPERATION_FLAGS Flags
);
NTSTATUS MfInstanceSetup(
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_SETUP_FLAGS Flags,
_In_ DEVICE_TYPE VolumeDeviceType,
_In_ FLT_FILESYSTEM_TYPE VolumeFilesystemType
);
NTSTATUS MfInstanceQueryTeardown (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags
);
VOID MfInstanceTeardownStart (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
);
VOID MfInstanceTeardownComplete (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
);
VOID MfDeleteTxfContext(
_Inout_ PFLT_CONTEXT Context,
_In_ FLT_CONTEXT_TYPE ContextType
);
NTSTATUS MfUnload(
_In_ FLT_FILTER_UNLOAD_FLAGS Flags
);
NTSTATUS MfQueryTearDown(
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags
);
NTSTATUS MfInstanceQueryTeardown(
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags
);
MiniFilter.c
#include "MiniFilter.h"
FLT_PREOP_CALLBACK_STATUS MfPreOperationCallback(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
)
{
UNREFERENCED_PARAMETER(Data);
UNREFERENCED_PARAMETER(FltObjects);
UNREFERENCED_PARAMETER(CompletionContext);
KdPrint(("MINIFILTER PreOperationCallback\n"));
return FLT_PREOP_SUCCESS_WITH_CALLBACK;
}
FLT_POSTOP_CALLBACK_STATUS MfPostOperationCallback(
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ PVOID CompletionContext,
_In_ FLT_POST_OPERATION_FLAGS Flags
)
{
UNREFERENCED_PARAMETER(Data);
UNREFERENCED_PARAMETER(FltObjects);
UNREFERENCED_PARAMETER(CompletionContext);
UNREFERENCED_PARAMETER(Flags);
KdPrint(("MINIFILTER PostOperationCallback\n"));
return FLT_POSTOP_FINISHED_PROCESSING;
}
VOID MfDeleteTxfContext(
_Inout_ PFLT_CONTEXT Context,
_In_ FLT_CONTEXT_TYPE ContextType
)
{
UNREFERENCED_PARAMETER(Context);
UNREFERENCED_PARAMETER(ContextType);
KdPrint(("MINIFILTER DeleteTxfContext\n"));
}
NTSTATUS
MfInstanceSetup (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_SETUP_FLAGS Flags,
_In_ DEVICE_TYPE VolumeDeviceType,
_In_ FLT_FILESYSTEM_TYPE VolumeFilesystemType
)
{
UNREFERENCED_PARAMETER( FltObjects );
UNREFERENCED_PARAMETER( Flags );
UNREFERENCED_PARAMETER( VolumeDeviceType );
UNREFERENCED_PARAMETER( VolumeFilesystemType );
PAGED_CODE();
KdPrint(("PassThrough!PtInstanceSetup: Entered\n") );
return STATUS_SUCCESS;
}
NTSTATUS
MfInstanceQueryTeardown (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags
)
{
UNREFERENCED_PARAMETER( FltObjects );
UNREFERENCED_PARAMETER( Flags );
PAGED_CODE();
KdPrint(("PassThrough!PtInstanceQueryTeardown: Entered\n") );
return STATUS_SUCCESS;
}
VOID
MfInstanceTeardownStart (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
)
{
UNREFERENCED_PARAMETER( FltObjects );
UNREFERENCED_PARAMETER( Flags );
PAGED_CODE();
KdPrint(("PassThrough!PtInstanceTeardownStart: Entered\n") );
}
VOID
MfInstanceTeardownComplete (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
)
{
UNREFERENCED_PARAMETER( FltObjects );
UNREFERENCED_PARAMETER( Flags );
PAGED_CODE();
KdPrint(("PassThrough!PtInstanceTeardownComplete: Entered\n") );
}
Does anyone see what's going on ?
I solved my problem : I had the wrong flag in my inf file. The good one is 0x0 flag in order to attach the minifilter automatically to the different volumes.
Instance1.Flags = 0x1 ; Suppress automatic attachments
to
Instance1.Flags = 0x0 ; Automatic attachments

How to detect if SendMessage() API is called

I have the first program (written in Win32 API) using a lot of SendMessage() API; it's already done and works.
The problem is I want to write a second one that can detect SendMessage() is called in the first program and if possible, capture its data (HANDLE, WPARAM, LPARAM...)
Does anyone know solution for this problem?
The DLLStudy.dll:
EDIT: ok, this is what I have so far.
#include <windows.h>
#define SIZE 6
typedef int (WINAPI *pMessageBoxW)(HWND, LPCWSTR, LPCWSTR, UINT);
int WINAPI MyMessageBoxW(HWND, LPCWSTR, LPCWSTR, UINT);
void BeginRedirect(LPVOID);
pMessageBoxW pOrigMBAddress = NULL;
BYTE oldBytes[SIZE] = {0};
BYTE JMP[SIZE] = {0};
DWORD oldProtect, myProtect = PAGE_EXECUTE_READWRITE;
INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved)
{
switch(Reason)
{
case DLL_PROCESS_ATTACH:
MessageBoxA(NULL, "Test", "OK", MB_OK);
pOrigMBAddress = (pMessageBoxW)
GetProcAddress(GetModuleHandle(L"user32.dll"), "MessageBoxW");
if(pOrigMBAddress != NULL)
BeginRedirect(MyMessageBoxW);
break;
case DLL_PROCESS_DETACH:
memcpy(pOrigMBAddress, oldBytes, SIZE);
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
void BeginRedirect(LPVOID newFunction)
{
BYTE tempJMP[SIZE] = {0xE9, 0x90, 0x90, 0x90, 0x90, 0xC3};
memcpy(JMP, tempJMP, SIZE);
DWORD JMPSize = ((DWORD)newFunction - (DWORD)pOrigMBAddress - 5);
VirtualProtect((LPVOID)pOrigMBAddress, SIZE,
PAGE_EXECUTE_READWRITE, &oldProtect);
memcpy(oldBytes, pOrigMBAddress, SIZE);
memcpy(&JMP[1], &JMPSize, 4);
memcpy(pOrigMBAddress, JMP, SIZE);
VirtualProtect((LPVOID)pOrigMBAddress, SIZE, oldProtect, NULL);
}
int WINAPI MyMessageBoxW(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uiType)
{
VirtualProtect((LPVOID)pOrigMBAddress, SIZE, myProtect, NULL);
memcpy(pOrigMBAddress, oldBytes, SIZE);
int retValue = MessageBoxW(hWnd, lpText, lpCaption, uiType);
memcpy(pOrigMBAddress, JMP, SIZE);
VirtualProtect((LPVOID)pOrigMBAddress, SIZE, oldProtect, NULL);
return retValue;
}
The Injector.cpp
#include <windows.h>
#include <iostream>
using namespace std;
char const Path[]="DLLStudy.dll";
int main(int argc, char* argv)
{
HANDLE hWnd, hProcess, AllocAdresse, hRemoteThread;
DWORD PID;
hWnd = FindWindow(0,"Notepad");
GetWindowThreadProcessId((HWND)hWnd, &PID);
hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, PID);
AllocAdresse = VirtualAllocEx(hProcess, 0, sizeof(Path), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(hProcess, (void*)AllocAdresse, (void*)Path, sizeof(Path), 0);
hRemoteThread=CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE) GetProcAddress(GetModuleHandle("kernel32.dll"),"LoadLibraryA"), AllocAdresse, 0, 0);
WaitForSingleObject(hRemoteThread, INFINITE);
VirtualFreeEx(hProcess, AllocAdresse, sizeof(Path), MEM_DECOMMIT);
CloseHandle(hProcess);
}
EDIT 2: Well, I've managed to make it work. So how to get data from SendMessage() if it is called?
You need to use CreateRemoteThread to inject a DLL into the first application. In the DLL's entrymain, you'd write code to remap the external call to SendMessage to your own SendMessageX which can then tell your other application when SendMessage is being called, and then pass the original call to the WIN32 subsystem.

Resources