API Hook Engine Module (Windows)

Share your advanced PureBasic knowledge/code with the community.
User avatar
chi
Addict
Addict
Posts: 1028
Joined: Sat May 05, 2007 5:31 pm
Location: Linz, Austria

Re: API Hook Engine Module (Windows)

Post by chi »

Your code was a little bit messy, but worked OK on x86 + x64... Here is a cleaned version ;)

Code: Select all

XIncludeFile "API_HookEngine.pbi"

Global *LoadLibrary

Procedure LoadLibrary__(lpFileName$) 
  Debug "Calling LoadLibrary(" + lpFileName$ + ")" 
  ; If lpFileName$ = "RICHED20.DLL"
  ;   ProcedureReturn 0
  ; EndIf  
  Protected func = UnHook(*LoadLibrary)
  Protected retn = CallFunctionFast(func, @lpFileName$)
  *LoadLibrary = Hook(func, @LoadLibrary__())
  ProcedureReturn retn  
EndProcedure

*LoadLibrary = Hook(ProcAddress("kernel32.dll", "LoadLibraryW"), @LoadLibrary__())

OpenWindow(0, 0, 0, 320, 200, "", #PB_Window_SystemMenu|#PB_Window_ScreenCentered)
EditorGadget(0, 10, 10, 300, 180)
While WaitWindowEvent() <> #PB_Event_CloseWindow : Wend

UnHook(*LoadLibrary)

Code: Select all

Calling LoadLibrary(C:\Windows\system32\ole32.dll)
Calling LoadLibrary(COMCTL32.DLL)
Calling LoadLibrary(uxtheme.dll)
Calling LoadLibrary(RICHED20.DLL)
Calling LoadLibrary(comctl32)
Calling LoadLibrary(ole32.dll)
FYI: If you want to skip loading "RICHED20.DLL" (for whatever reason?!?), you'll end up with a broken EditorGadget (no input)...
Et cetera is my worst enemy
User avatar
chi
Addict
Addict
Posts: 1028
Joined: Sat May 05, 2007 5:31 pm
Location: Linz, Austria

Re: API Hook Engine Module (Windows)

Post by chi »

Oh, I get it now! You want to load the dll from a different path than System32 (this post). Following snippet works for me...

Code: Select all

XIncludeFile "API_HookEngine.pbi"

Global *LoadLibrary

Procedure LoadLibrary__(lpFileName$) 
  If lpFileName$ = "RICHED20.DLL"
    lpFileName$ = "D:\Desktop\riched20.dll" ;edit your path here!
  EndIf
  Debug "Calling LoadLibrary(" + lpFileName$ + ")" 
  Protected func = UnHook(*LoadLibrary)
  Protected retn = CallFunctionFast(func, @lpFileName$)
  *LoadLibrary = Hook(func, @LoadLibrary__())
  ProcedureReturn retn  
EndProcedure

*LoadLibrary = Hook(ProcAddress("kernel32.dll", "LoadLibraryW"), @LoadLibrary__())

OpenWindow(0, 0, 0, 320, 200, "", #PB_Window_SystemMenu|#PB_Window_ScreenCentered)
EditorGadget(0, 10, 10, 300, 180)
While WaitWindowEvent() <> #PB_Event_CloseWindow : Wend

UnHook(*LoadLibrary)
Et cetera is my worst enemy
firace
Addict
Addict
Posts: 899
Joined: Wed Nov 09, 2011 8:58 am

Re: API Hook Engine Module (Windows)

Post by firace »

chi, thanks a lot for your help. I have extended your example by hooking LoadLibraryEx as well, which shows some more DLLs being loaded (for instance by the WebGadget). However I still don't see the one I'm specifically looking for (vbscript.dll). By any chance, would you know it there are other methods that the OS uses to load DLLs that I am not aware of? It seems that LoadLibrary and LoadLibraryEx don't show everything.

This could be a tough nut to crack I'm afraid...

FYI, one (old) web page still calling vbscript.dll is https://www.apple.com/be. (I have verified that using Sysinternals tools)
But the page does work fine without that DLL in fact. The only way I have found to block that specific DLL from loading is to deny NTFS read&execute access on the DLL itself, but I'm not too happy with that solution as it requires admin rights and may impact other applications.

Code: Select all


IncludeFile "API_HookEngine.pbi"
UseModule API_HookEngine

Global *LoadLibrary

Procedure LoadLibraryEx__(lpFileName$, handle, flags) 
  Debug "Calling LoadLibrary(" + lpFileName$ + ")" 
  If lpFileName$ = "jscript.dll" Or lpFileName$ = "vbscript.dll"
    Beep_(3131,412)
  ProcedureReturn 0
   EndIf  
  Protected func = UnHook(*LoadLibrary)
  Protected retn = CallFunctionFast(func, @lpFileName$, handle, flags)
  *LoadLibrary = Hook(func, @LoadLibraryEx__())
  ProcedureReturn retn  
EndProcedure

Procedure LoadLibrary__(lpFileName$) 
  Debug "Calling LoadLibrary(" + lpFileName$ + ")" 
  ; If lpFileName$ = "RICHED20.DLL"
  ;   ProcedureReturn 0
  ; EndIf  
  Protected func = UnHook(*LoadLibrary)
  Protected retn = CallFunctionFast(func, @lpFileName$)
  *LoadLibrary = Hook(func, @LoadLibrary__())
  ProcedureReturn retn  
EndProcedure



*LoadLibrary = Hook(ProcAddress("kernel32.dll", "LoadLibraryExW"), @LoadLibraryEx__())

; *LoadLibrary = Hook(ProcAddress("kernel32.dll", "LoadLibraryW"), @LoadLibrary__())


OpenWindow(0, 0, 0, 620, 400, "", #PB_Window_SystemMenu|#PB_Window_ScreenCentered)
WebGadget(1,40,40,500,400,"https://www.apple.com/be")
While WaitWindowEvent() <> #PB_Event_CloseWindow : Wend

UnHook(*LoadLibrary)

User avatar
chi
Addict
Addict
Posts: 1028
Joined: Sat May 05, 2007 5:31 pm
Location: Linz, Austria

Re: API Hook Engine Module (Windows)

Post by chi »

Hi firace,

I'm sorry, but I can't reproduce the loading of vbscript.dll with the WebGadget... All I found with API Monitor was a reference to jscript.dll (CoCreateInstance, ...) and with Process Hacker following dlls:
Since the WebGadget was loaded with "OleCreate(Microsoft Web Browser <Shell.Explorer.2>, ...)" maybe take a closer look at COM (Ole32.dll)

Code: Select all

web.exe, 0x400000, 64 kB, 
advapi32.dll, 0x75ac0000, 644 kB, Advanced Windows 32 Base API
api-ms-win-core-synch-l1-2-0.dll, 0x6e360000, 12 kB, ApiSet Stub DLL
apisetschema.dll, 0x40000, 4 kB, ApiSet Schema DLL
apphelp.dll, 0x712f0000, 304 kB, Application Compatibility Client Library
atl.dll, 0x6a920000, 80 kB, ATL Module for Windows XP (Unicode)
AudioSes.dll, 0x71d50000, 216 kB, Audio Session
avrt.dll, 0x71200000, 28 kB, Multimedia Realtime Runtime
bcrypt.dll, 0x6c520000, 92 kB, Windows Cryptographic Primitives Library (Wow64)
bcryptprimitives.dll, 0x6c4e0000, 244 kB, Windows Cryptographic Primitives Library
cfgmgr32.dll, 0x77720000, 156 kB, Configuration Manager DLL
clbcatq.dll, 0x75b70000, 524 kB, COM+ Configuration Catalog
comctl32.dll, 0x73180000, 1,62 MB, User Experience Controls Library
credssp.dll, 0x6a770000, 32 kB, Credential Delegation Security Package
crypt32.dll, 0x76a40000, 1,13 MB, Crypto API32
crypt32.dll.mui, 0x27e0000, 40 kB, Crypto API32
cryptbase.dll, 0x758a0000, 48 kB, Base cryptographic API DLL
cryptnet.dll, 0x658e0000, 116 kB, Crypto Network Related API
cryptsp.dll, 0x6c940000, 92 kB, Cryptographic Service Provider API
C_20127.NLS, 0x34c0000, 68 kB, 
dciman32.dll, 0x6f410000, 24 kB, DCI Manager
ddraw.dll, 0x6f420000, 924 kB, Microsoft DirectDraw
ddraw.dll.mui, 0x5520000, 4 kB, Microsoft DirectDraw
ddrawex.dll, 0x6f510000, 40 kB, Direct Draw Ex
devobj.dll, 0x76980000, 72 kB, Device Information Set DLL
dnsapi.dll, 0x6ca40000, 272 kB, DNS Client API DLL
dwmapi.dll, 0x73040000, 76 kB, Microsoft Desktop Window Manager API
dxtmsft.dll, 0x6e300000, 348 kB, DirectX Media -- Image DirectX Transforms
dxtrans.dll, 0x6f520000, 228 kB, DirectX Media -- DirectX Transform Core
FWPUCLNT.DLL, 0x6a870000, 224 kB, FWP/IPsec User-Mode API
gdi32.dll, 0x768f0000, 576 kB, GDI Client DLL
GdiPlus.dll, 0x72b80000, 1,57 MB, Microsoft GDI+
gpapi.dll, 0x65900000, 88 kB, Group Policy Client API
ieframe.dll, 0x6fcf0000, 10,54 MB, Internet Browser
ieframe.dll.mui, 0x2550000, 1,19 MB, Internet Browser
iertutil.dll, 0x76be0000, 2 MB, Run time utility for Internet Explorer
imgutil.dll, 0x6f570000, 44 kB, IE plugin image decoder support DLL
imm32.dll, 0x76df0000, 384 kB, Multi-User Windows IMM32 API Client DLL
index.dat, 0x2d0000, 32 kB, 
index.dat, 0x480000, 176 kB, 
index.dat, 0x2350000, 1,36 MB, 
index.dat, 0x3c40000, 32 kB, 
index.dat, 0x98c0000, 48 kB, 
IPHLPAPI.DLL, 0x73160000, 112 kB, IP Helper API
jscript.dll, 0x6f580000, 712 kB, Microsoft ® JScript
jscript.dll.mui, 0x34e0000, 16 kB, Microsoft ® JScript
kernel32.dll, 0x75910000, 1,06 MB, Windows NT BASE API Client DLL
KernelBase.dll, 0x77290000, 284 kB, Windows NT BASE API Client DLL
KernelBase.dll.mui, 0x48f0000, 768 kB, Windows NT BASE API Client DLL
ksuser.dll, 0x6a8b0000, 16 kB, User CSA Library
locale.nls, 0x410000, 412 kB, 
lpk.dll, 0x76e50000, 40 kB, Language Pack
midimap.dll, 0x6f640000, 28 kB, Microsoft MIDI Mapper
mlang.dll, 0x6f6b0000, 184 kB, Multi Language Support DLL
mlang.dll.mui, 0x1de0000, 16 kB, Multi Language Support DLL
MMDevAPI.dll, 0x71d90000, 228 kB, MMDevice API
MMDevAPI.dll.mui, 0x2680000, 4 kB, MMDevice API
msacm32.dll, 0x72850000, 80 kB, Microsoft ACM Audio Filter
msacm32.drv, 0x6f650000, 32 kB, Microsoft Sound Mapper
msasn1.dll, 0x774c0000, 48 kB, ASN.1 Runtime APIs
msctf.dll, 0x77750000, 820 kB, MSCTF Server DLL
mshtml.dll, 0x6f720000, 5,77 MB, Microsoft (R) HTML Viewer
mshtml.dll.mui, 0x5460000, 4 kB, Microsoft (R) HTML Viewer
mshtml.tlb, 0x4750000, 1,57 MB, Microsoft® MSHTML Typelib
msimg32.dll, 0x73530000, 20 kB, GDIEXT Client DLL
msimtf.dll, 0x6f6e0000, 44 kB, Active IMM Server DLL
msls31.dll, 0x6f6f0000, 168 kB, Microsoft Line Services library file
msvcrt.dll, 0x772e0000, 688 kB, Windows NT CRT DLL
mswsock.dll, 0x72180000, 240 kB, Microsoft Windows Sockets 2.0 Service Provider
NapiNSP.dll, 0x6ca20000, 64 kB, E-mail Naming Shim Provider
ncrypt.dll, 0x6ad90000, 228 kB, Windows cryptographic library
nlaapi.dll, 0x6ca30000, 64 kB, Network Location Awareness 2
normaliz.dll, 0x76b70000, 12 kB, Unicode Normalization DLL
nsi.dll, 0x779c0000, 24 kB, NSI User-mode interface DLL
ntdll.dll, 0x77bf0000, 1,62 MB, NT Layer DLL
ntdll.dll, 0x77db0000, 1,5 MB, NT Layer DLL
ntmarta.dll, 0x72f10000, 132 kB, Windows NT MARTA provider
nvd3dum.dll, 0x6e370000, 16,61 MB, NVIDIA WDDM D3D Driver, Version 418.99 
ole32.dll, 0x77000000, 1,37 MB, Microsoft OLE for Windows
oleacc.dll, 0x734f0000, 240 kB, Active Accessibility Core Component
oleaccrc.dll, 0x1f0000, 4 kB, Active Accessibility Resource DLL
oleaut32.dll, 0x774d0000, 580 kB, 
pngfilt.dll, 0x6f560000, 56 kB, IE PNG plugin image decoder
pnrpnsp.dll, 0x6ca00000, 72 kB, PNRP Name Space Provider
powrprof.dll, 0x73940000, 148 kB, Power Profile Helper DLL
profapi.dll, 0x6cbd0000, 44 kB, User Profile Basic API
propsys.dll, 0x72f40000, 980 kB, Microsoft Property System
psapi.dll, 0x768e0000, 20 kB, Process Status Helper
rasadhlp.dll, 0x6a940000, 24 kB, Remote Access AutoDial Helper
rasapi32.dll, 0x6a9c0000, 328 kB, Remote Access API
rasman.dll, 0x6a9a0000, 84 kB, Remote Access Connection Manager
rpcrt4.dll, 0x77160000, 960 kB, Remote Procedure Call Runtime
RpcRtRemote.dll, 0x6c8f0000, 56 kB, Remote RPC Extension
rsaenh.dll, 0x6c900000, 236 kB, Microsoft Enhanced Cryptographic Provider
rtutils.dll, 0x6f670000, 52 kB, Routing Utilities
schannel.dll, 0x70c20000, 260 kB, TLS / SSL Security Provider
sechost.dll, 0x76a20000, 100 kB, Host for SCM/SDDL/LSA Lookup APIs
secur32.dll, 0x73430000, 32 kB, Security Support Provider Interface
SensApi.dll, 0x6f660000, 24 kB, SENS Connectivity API DLL
setupapi.dll, 0x77820000, 1,61 MB, Windows Setup API
setupapi.dll.mui, 0x24f0000, 52 kB, Windows Setup API
shell32.dll, 0x75c00000, 12,3 MB, Windows Shell Common Dll
shell32.dll.mui, 0x5400000, 368 kB, Windows Shell Common Dll
shlwapi.dll, 0x76b80000, 348 kB, Shell Light-weight Utility Library
SortDefault.nls, 0x1f80000, 2,81 MB, 
sspicli.dll, 0x758b0000, 384 kB, Security Support Provider Interface
StaticCache.dat, 0x5d70000, 9,31 MB, 
stdole2.tlb, 0x27f0000, 16 kB, 
sxs.dll, 0x71cf0000, 380 kB, Fusion 2.5
t2embed.dll, 0x6e2e0000, 120 kB, Microsoft T2Embed Font Embedding
urlmon.dll, 0x76e60000, 1,25 MB, OLE32 Extensions for Win32
urlmon.dll.mui, 0x4b0000, 32 kB, OLE32 Extensions for Win32
user32.dll, 0x773c0000, 1 MB, Multi-User Windows USER API Client DLL
user32.dll.mui, 0x3d50000, 20 kB, Multi-User Windows USER API Client DLL
userenv.dll, 0x6cbe0000, 92 kB, Userenv
usp10.dll, 0x75a20000, 628 kB, Uniscribe Unicode script processor
uxtheme.dll, 0x73060000, 512 kB, Microsoft UxTheme Library
version.dll, 0x73140000, 36 kB, Version Checking and File Installation Libraries
wdmaud.drv, 0x6f680000, 192 kB, Winmm  audio system driver
wdmaud.drv.mui, 0x2500000, 4 kB, Winmm  audio system driver
wininet.dll, 0x77570000, 980 kB, Internet Extensions for Win32
winmm.dll, 0x739f0000, 200 kB, MCI API DLL
winmm.dll.mui, 0x1df0000, 24 kB, MCI API DLL
winnsi.dll, 0x73150000, 28 kB, Network Store Information RPC interface
winrnr.dll, 0x6c9f0000, 32 kB, LDAP RnR Provider DLL
wintrust.dll, 0x77670000, 188 kB, Microsoft Trust Verification APIs
Wldap32.dll, 0x769d0000, 276 kB, Win32 LDAP API DLL
wow64.dll, 0x73380000, 252 kB, Win32 Emulation on NT64
wow64cpu.dll, 0x756d0000, 32 kB, AMD64 Wow64 CPU 
wow64win.dll, 0x73320000, 368 kB, Wow64 Console and Win32 API Logging
ws2_32.dll, 0x77250000, 212 kB, Windows Socket 2.0 32-Bit DLL
wship6.dll, 0x72160000, 24 kB, Winsock2 Helper DLL (TL/IPv6)
WSHTCPIP.DLL, 0x733e0000, 20 kB, Winsock2 Helper DLL (TL/IPv4)
xmllite.dll, 0x769a0000, 188 kB, Microsoft XmlLite Library
{AFBF9F1A-8EE8-4C77-AF34-C647E37CA0D9}.1.ver0x00000000000002dd.db, 0x98d0000, 124 kB, 
[/size]
Et cetera is my worst enemy
firace
Addict
Addict
Posts: 899
Joined: Wed Nov 09, 2011 8:58 am

Re: API Hook Engine Module (Windows)

Post by firace »

Thanks for your additional tests!
Not sure why you are not getting the vbscript.dll call. But in fact I'm also interested in jscript.dll :)
Any ideas on how to hook the CoCreateInstance function? If too tricky / time-consuming, nevermind, I will perhaps give up on this idea and look for a totally different approach.
User avatar
chi
Addict
Addict
Posts: 1028
Joined: Sat May 05, 2007 5:31 pm
Location: Linz, Austria

Re: API Hook Engine Module (Windows)

Post by chi »

I'm not a COM guy, so I have no clue what I'm doing... ;)

Code: Select all

Global *CoCreateInstance

Procedure.s StringFromCLSID(*clsid.iid)  
  ;from mk-soft: https://www.purebasic.fr/german/viewtopic.php?p=213506&sid=ba54e4e7f1ad02efbf0fdbe478ce2191#p213506

  Protected result.s, i, b
  result = "{"
  result + RSet(Hex(*clsid\data1),8,"0")
  result + "-" + RSet(Hex(*clsid\data2),4,"0")
  result + "-" + RSet(Hex(*clsid\data3),4,"0")
  result + "-"
  b = *clsid\data4[0] & $FF
  result + RSet(Hex(b),2,"0")
  b = *clsid\data4[1] & $FF
  result + RSet(Hex(b),2,"0")
  result + "-"
  For i = 2 To 7
    b = *clsid\data4[i] & $FF
    result + RSet(Hex(b),2,"0")
  Next
  result + "}"
  ProcedureReturn result
EndProcedure

Procedure CoCreateInstance__(*rclsid.CLSID, pUnkOuter, dwClsContext, *riid.CLSID, *ppv)
  Debug StringFromCLSID(*rclsid)
  Protected func = UnHook(*CoCreateInstance)
  Protected retn = CallFunctionFast(func, *rclsid, pUnkOuter, dwClsContext, *riid, *ppv)
  *CoCreateInstance = Hook(func, @CoCreateInstance__())
  ProcedureReturn retn   
EndProcedure

*CoCreateInstance = Hook(ProcAddress("ole32.dll", "CoCreateInstance"), @CoCreateInstance__())
Et cetera is my worst enemy
firace
Addict
Addict
Posts: 899
Joined: Wed Nov 09, 2011 8:58 am

Re: API Hook Engine Module (Windows)

Post by firace »

Coming back to my crazy hooking experiments!

First of all, late thanks to chi for the helpful CoCreateInstance example :)


However, the below code crashes after a few seconds, at line 118 (FreeMemory(*hook_ptr)) .
Any ideas on how to fix the crash? (Note: at this stage my goal is just to log the CoCreateInstance calls, not block or modify them in any way)
Thanks for any feedback!

Note: I'm getting the same behavior in both 32-bit and 64-bit, with the threadsafe option enabled.

Code: Select all

; ====================================================================================================
; Title:        API_HookEngine Module
; Description:  With this module you can hook procedures and api in windows
; Author:       Peyman
; Version:      1.0 (02 FEB 2016) initial version
;               1.1 (07 FEB 2016) added Inject DLL
;               1.2 (11 FEB 2016) improved injector, added Eject DLL & CallRemoteFunction with parrameter
; Platform:     Windows (X64 And X86) Unicode And Ansi
; License:      Free But Any improvements to be shared with the community.
; ====================================================================================================

DeclareModule API_HookEngine
  Declare.i Hook(*OldFunctionAddress, *NewFunctionAddress)
  Declare.i UnHook(*hook_ptr)
  Declare.i ProcAddress(ModuleName$, ProcName$)
EndDeclareModule


Module API_HookEngine  
  EnableExplicit
  
  CompilerIf #PB_Compiler_Processor = #PB_Processor_x64
    #INJECTOR_IS_64 = #True
  CompilerElse
    #INJECTOR_IS_64 = #False
  CompilerEndIf
  
  
  Structure opcode
    CompilerIf #PB_Compiler_Processor = #PB_Processor_x64
      mov.u
    CompilerElse
      mov.a
    CompilerEndIf
    addr.i
    push.a
    ret.a
  EndStructure
  
  
  Structure hookstruct
    addr.i
    hook.opcode
    orig.a[SizeOf(opcode)]
  EndStructure
  
  
  CompilerIf #PB_Compiler_Unicode
    Import "kernel32.lib"
      GetProcAddress(hModule, lpProcName.p-ascii)
    EndImport
  CompilerElse
    Import "kernel32.lib"
      GetProcAddress(hModule, lpProcName.s)
    EndImport
  CompilerEndIf
  
  
  Import ""
    GetNativeSystemInfo(*info)
  EndImport
  
  
  Procedure.i ProcAddress(ModuleName$, ProcName$)
    Protected moduleH.i
    
    moduleH = GetModuleHandle_(ModuleName$)
    If moduleH = #Null
      moduleH = LoadLibrary_(ModuleName$)
      If moduleH = #Null
        ProcedureReturn #Null
      EndIf
    EndIf
    
    ProcedureReturn GetProcAddress(moduleH, ProcName$)
  EndProcedure
  
  
  Procedure Hook(*OldFunctionAddress, *NewFunctionAddress)
    Protected *hook_ptr.hookstruct
    
    If Not *OldFunctionAddress
      ProcedureReturn #Null
    EndIf
    
    *hook_ptr = AllocateMemory(SizeOf(hookstruct))
    *hook_ptr\addr = *OldFunctionAddress
    CompilerIf #PB_Compiler_Processor = #PB_Processor_x64
      *hook_ptr\hook\mov = $B848
    CompilerElse
      *hook_ptr\hook\mov = $B8
    CompilerEndIf
    *hook_ptr\hook\addr = *NewFunctionAddress
    *hook_ptr\hook\push = $50
    *hook_ptr\hook\ret = $C3
    
    CopyMemory(*OldFunctionAddress, @*hook_ptr\orig, SizeOf(opcode))
    If Not WriteProcessMemory_(GetCurrentProcess_(), *OldFunctionAddress, @*hook_ptr\hook, SizeOf(opcode), #Null)
      FreeMemory(*hook_ptr)
      ProcedureReturn #Null
    Else
      ProcedureReturn *hook_ptr
    EndIf
  EndProcedure
  
  
  Procedure.i UnHook(*hook_ptr.hookstruct)
    Protected retValue.i
    
    If *hook_ptr
      If *hook_ptr\addr
        If WriteProcessMemory_(GetCurrentProcess_(), *hook_ptr\addr, @*hook_ptr\orig, SizeOf(opcode), #Null)
          retValue = *hook_ptr\addr
          if *hook_ptr
            FreeMemory(*hook_ptr)
          endif
          ProcedureReturn retValue
        EndIf
      EndIf
    EndIf
    
    ProcedureReturn #Null
  EndProcedure
  
  
EndModule



UseModule API_HookEngine





Global *CoCreateInstance

Procedure.s StringFromCLSID(*clsid.iid)  
  ;from mk-soft: https://www.purebasic.fr/german/viewtopic.php?p=213506&sid=ba54e4e7f1ad02efbf0fdbe478ce2191#p213506
  
  Protected result.s, i, b
  result = "{"
  result + RSet(Hex(*clsid\data1),8,"0")
  result + "-" + RSet(Hex(*clsid\data2),4,"0")
  result + "-" + RSet(Hex(*clsid\data3),4,"0")
  result + "-"
  b = *clsid\data4[0] & $FF
  result + RSet(Hex(b),2,"0")
  b = *clsid\data4[1] & $FF
  result + RSet(Hex(b),2,"0")
  result + "-"
  For i = 2 To 7
    b = *clsid\data4[i] & $FF
    result + RSet(Hex(b),2,"0")
  Next
  result + "}"
  ProcedureReturn result
EndProcedure

Procedure CoCreateInstance__(*rclsid.CLSID, pUnkOuter, dwClsContext, *riid.CLSID, *ppv)
  Debug StringFromCLSID(*rclsid)
  Protected func = UnHook(*CoCreateInstance)
  Protected retn = CallFunctionFast(func, *rclsid, pUnkOuter, dwClsContext, *riid, *ppv)
  *CoCreateInstance = Hook(func, @CoCreateInstance__())
  ProcedureReturn retn   
EndProcedure

*CoCreateInstance = Hook(ProcAddress("ole32.dll", "CoCreateInstance"), @CoCreateInstance__())


OpenWindow(0, 0, 0, 620, 400, "", #PB_Window_SystemMenu|#PB_Window_ScreenCentered)
WebGadget(1,40,40,500,400,"https://www.bing.com/")
While WaitWindowEvent() <> #PB_Event_CloseWindow : Wend

UnHook(*LoadLibrary)
Last edited by firace on Sat Jan 25, 2020 6:58 pm, edited 2 times in total.
firace
Addict
Addict
Posts: 899
Joined: Wed Nov 09, 2011 8:58 am

Re: API Hook Engine Module (Windows)

Post by firace »

According to the help file, the WriteProcessMemory_ call 5 lines above could be writing to the wrong memory area... But no idea how to go on from there :(
fryquez
Enthusiast
Enthusiast
Posts: 362
Joined: Mon Dec 21, 2015 8:12 pm

Re: API Hook Engine Module (Windows)

Post by fryquez »

Threadsafe option is necessary, but will not help as this hooking engine is not thread safe.

Use Detours or MinHook.
User avatar
chi
Addict
Addict
Posts: 1028
Joined: Sat May 05, 2007 5:31 pm
Location: Linz, Austria

Re: API Hook Engine Module (Windows)

Post by chi »

I have no crashes (x86/x64, threadsave on/off). But use MinHook! With MinHook you don't need to unhook/hook to call the original procedure...
Et cetera is my worst enemy
firace
Addict
Addict
Posts: 899
Joined: Wed Nov 09, 2011 8:58 am

Re: API Hook Engine Module (Windows)

Post by firace »

Thanks for your advice, so I will definitely check out MinHook :)
I wasn't able to find any PB examples though, but I will look into it.
firace
Addict
Addict
Posts: 899
Joined: Wed Nov 09, 2011 8:58 am

Re: API Hook Engine Module (Windows)

Post by firace »

I threw together a (very sloppy) first attempt at hooking MessageBoxW, but no luck yet:

Code: Select all


Import "MinHook.x64.lib"  
MH_Initialize()                                                 As "MH_Initialize"
  MH_CreateHookApiEx(a.s,b.s,pCallback.i,pOriginal.i,pTarget.i)   As "MH_CreateHookApiEx"
  MH_EnableHook(a.i)                                              As "MH_EnableHook"
  
  MH_DisableHook(a.i)                                             As "MH_DisableHook"
  MH_Uninitialize()                                               As "MH_UnInitialize"
EndImport

Import "kernel32.lib"
  GetProcAddress(hModule, lpProcName.p-ascii)
EndImport

Procedure.i ProcAddress(ModuleName$, ProcName$)
  Protected moduleH.i
  
  moduleH = GetModuleHandle_(ModuleName$)
  If moduleH = #Null
    moduleH = LoadLibrary_(ModuleName$)
    If moduleH = #Null
      ProcedureReturn #Null
    EndIf
  EndIf
  
  ProcedureReturn GetProcAddress(moduleH, ProcName$)
EndProcedure


Procedure myMsgBox()
  
  debug "Hello"
  beep_(3232,232)
EndProcedure     

MH_Initialize()
debug  MH_CreateHookApiEx("user32.dll","MessageBoxW",@myMsgBox(),@original, @tgt)
debug @tgt
; debug MH_EnableHook(ProcAddress("user32.dll", "MessageBoxW"))
debug MH_EnableHook(@tgt)

delay(200)
messageBox_(0,"test","test",0)

User avatar
chi
Addict
Addict
Posts: 1028
Joined: Sat May 05, 2007 5:31 pm
Location: Linz, Austria

Re: API Hook Engine Module (Windows)

Post by chi »

Here is a working example...

Code: Select all

CompilerIf #PB_Compiler_Processor = #PB_Processor_x64
  #lib$ = "libMinHook.x64.lib"
CompilerElse
  #lib$ = "libMinHook.x86.lib"
CompilerEndIf

Import #lib$
  MH_Initialize()
  MH_CreateHook(*pTarget, *pDetour, *ppOriginal)
  MH_CreateHookApiEx(pszModule.p-unicode, pszProcName.p-ascii, *pDetour, *ppOriginal, *ppTarget)
  MH_EnableHook(*pTarget)
  MH_DisableHook(*pTarget)
  MH_RemoveHook(*pTarget)
  MH_QueueEnableHook(*pTarget)
  MH_QueueDisableHook(*pTarget)
  MH_ApplyQueued()
  MH_Uninitialize()
EndImport

#MH_ALL_HOOKS = 0

Prototype _Beep(dwFreq, dwDuration) : Global Beep._Beep
Procedure Beep__(dwFreq, dwDuration)
  Debug "" + dwFreq + #LF$ + dwDuration
  ProcedureReturn Beep(dwFreq, dwDuration)
EndProcedure

Prototype _MessageBox(hWnd, lpText.s, lpCaption.s, uType) : Global MessageBox._MessageBox
Procedure MessageBox__(hWnd, lpText.s, lpCaption.s, uType)
  Debug lpCaption + #LF$ + lpText
  ProcedureReturn MessageBox(hWnd, lpText, lpCaption, uType)
EndProcedure

MH_Initialize()
MH_CreateHookApiEx("kernel32" , "Beep", @Beep__(), @Beep, #Null)
MH_CreateHookApiEx("user32" , "MessageBoxW", @MessageBox__(), @MessageBox, #Null)
MH_EnableHook(#MH_ALL_HOOKS)

Beep_(800, 50)
MessageRequester("Title", "Text", #PB_MessageRequester_Info)

MH_DisableHook(#MH_ALL_HOOKS)
MH_Uninitialize()
Et cetera is my worst enemy
firace
Addict
Addict
Posts: 899
Joined: Wed Nov 09, 2011 8:58 am

Re: API Hook Engine Module (Windows)

Post by firace »

Fantastic, thank you so much chi!
User avatar
chi
Addict
Addict
Posts: 1028
Joined: Sat May 05, 2007 5:31 pm
Location: Linz, Austria

Re: API Hook Engine Module (Windows)

Post by chi »

firace wrote:Fantastic, thank you so much chi!
No problem :D
Et cetera is my worst enemy
Post Reply