(Python) Hook Injection by Unprotect

Created the Tuesday 06 December 2022. Updated 1 year, 2 months ago.


The HookFunction is injected as a hook using the SetWindowsHookEx function, and it still calls the CallNextHookEx function to continue the normal flow of execution. The main function installs the hook, runs the message loop to receive events, and then uninstalls the hook when finished.


            import ctypes
from ctypes.wintypes import HHOOK, LPARAM, LRESULT, WPARAM

# The function to be injected as a hook
def HookFunction(code: int, wParam: WPARAM, lParam: LPARAM) -> LRESULT:
    # Perform malicious actions here

    # Return the result of the next hook in the chain
    return ctypes.windll.user32.CallNextHookEx(None, code, wParam, lParam)

def main():
    # Install the hook
    hHook = ctypes.windll.user32.SetWindowsHookEx(
        ctypes.c_int(14), HookFunction, None, 0

    # Run the message loop to receive events
    msg = ctypes.wintypes.MSG()
    while ctypes.windll.user32.GetMessageW(ctypes.byref(msg), None, 0, 0):

    # Uninstall the hook

if __name__ == "__main__":