Jump to content

The definition of the keyboard keys


Proton
 Share

Recommended Posts

One more question.

This code temporarily freezes the key after it is activated.

If _ispressed('41') = 1 And DllStructGetData($tRIH, "hDevice") = 0x00010049 Then
            _BlockInputEx(3, "", "[a]")
             AdlibRegister("_Quit", 10000)
             MsgBox(64, 'Result', 'key А - PS2')
EndIf

 

#include <BlockInputEx.au3>

http://www.autoitscript.com/forum/index.php?s=&showtopic=87735

How to prevent entering text from the keyboard (with handle number 0x00010049) from the moment the code is run ?

Link to comment
Share on other sites

For that you got multiple ways. :) 

The first solution i thought is to disable the port used by this device. 

USB/ps2

Never did it but i guess it s possible.

 

My video tutorials : ( In construction )  || My Discord : https://discord.gg/S9AnwHw

How to Ask Help ||  UIAutomation From Junkew || WebDriver From Danp2 || And Water's UDFs in the Quote

Spoiler

 Water's UDFs:
Active Directory (NEW 2018-10-19 - Version 1.4.10.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (2018-10-31 - Version 1.3.4.1) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Link to comment
Share on other sites

Have no idea, if you need to detect the key, then the code has to be able to "see" it, i think.

So if you block input it's like there is no key press.

Spoiler

Renamer - Rename files and folders, remove portions of text from the filename etc.

GPO Tool - Export/Import Group policy settings.

MirrorDir - Synchronize/Backup/Mirror Folders

BeatsPlayer - Music player.

Params Tool - Right click an exe to see it's parameters or execute them.

String Trigger - Triggers pasting text or applications or internet links on specific strings.

Inconspicuous - Hide files in plain sight, not fully encrypted.

Regedit Control - Registry browsing history, quickly jump into any saved key.

Time4Shutdown - Write the time for shutdown in minutes.

Power Profiles Tool - Set a profile as active, delete, duplicate, export and import.

Finished Task Shutdown - Shuts down pc when specified window/Wndl/process closes.

NetworkSpeedShutdown - Shuts down pc if download speed goes under "X" Kb/s.

IUIAutomation - Topic with framework and examples

Au3Record.exe

Link to comment
Share on other sites

argumentum,It doesn't work. When triggered, the script still prints an unnecessary "a".

;Bilgus 2018
;Determine which keyboard was pressed

#include <Array.au3>
#include <WinAPISys.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <Misc.au3>

Global Const $HWND_MESSAGE = (-3) ;create a message-only window when set as Parent

;RAWINPUTDEVICE Constants
Global Const $HID_USAGE_PAGE_GENERIC = 0x1
Global Const $HID_USAGE_GENERIC_KEYBOARD = 0x6

Global $ghSelectedDevice

Global $gaKeyboards = EnumRawKeyboards("\HID")

If IsArray($gaKeyboards) And $gaKeyboards[0][0] >= 1 Then $ghSelectedDevice = $gaKeyboards[1][0] ; hard coded change to suit

;_ArrayDisplay($gaKeyboards, '_WinAPI_EnumRawInputDevices', "", 0, Default, "Handle|Type|VID|Keys") ;Not Needed...

Global $hTarget = GUICreate("main", 10, 10, Default, Default, Default, Default, $HWND_MESSAGE) ;Dummy window to recieve messages

Register_RawInput($HID_USAGE_PAGE_GENERIC, $HID_USAGE_GENERIC_KEYBOARD, $RIDEV_INPUTSINK, $hTarget) ;$RIDEV_INPUTSINK recieves input when not foreground

; Register WM_INPUT message
GUIRegisterMsg($WM_INPUT, 'WM_INPUT')



While 1
    Sleep(1000)
WEnd

Func Device_Pressed()
    ConsoleWrite("Device Pressed" & @CRLF)
EndFunc   ;==>Device_Pressed

Func _Exit()
    Exit
EndFunc   ;==>_Exit

Func Register_RawInput($iUsagePage, $iUsage, $iFlags, $hTargetHwnd)
    Local $tRID = DllStructCreate($tagRAWINPUTDEVICE)
    DllStructSetData($tRID, 'UsagePage', $iUsagePage)
    DllStructSetData($tRID, 'Usage', $iUsage)
    DllStructSetData($tRID, 'Flags', $iFlags)
    DllStructSetData($tRID, 'hTarget', $hTargetHwnd)

    ; Register HID input to obtain info from devices
    _WinAPI_RegisterRawInputDevices($tRID)
EndFunc   ;==>Register_RawInput

Func WM_INPUT($hWnd, $iMsg, $wParam, $lParam) ;Callback from RawInput
    #forceref $iMsg, $wParam

   Local $tInfo, $aData = _WinAPI_EnumRawInputDevices()
   Local $_tagRID_INFO_KEYBOARD = $tagRID_INFO_KEYBOARD
   Local $tInfo, $tDeviceName, $sDeviceName


    ;'struct;dword Type;dword Size;handle hDevice;wparam wParam;endstruct'
    Local $tRIH = DllStructCreate($tagRAWINPUTHEADER)

     If _WinAPI_GetRawInputData($lParam, $tRIH, DllStructGetSize($tRIH), $RID_HEADER) And DllStructGetData($tRIH, "Type") = $RIM_TYPEKEYBOARD Then
        ;ConsoleWrite("0x" & Hex(DllStructGetData($tRIH, "hDevice")) & @CRLF)
        If $ghSelectedDevice = DllStructGetData($tRIH, "hDevice") Then
            ;ConsoleWrite("Device Pressed" & @CRLF)
        Else
            ;ConsoleWrite("Different Device Pressed" & @CRLF)
        EndIf
        If _ispressed('41') = 1 And DllStructGetData($tRIH, "hDevice") = 0x00010049 Then
            ;ConsoleWrite('Yes A' &@CRLF)
            MsgBox(64, 'Result', 'Key А - PS2')
         EndIf

        If _ispressed('41') = 1 And DllStructGetData($tRIH, "hDevice") = $HandleX Then
            ;ConsoleWrite('Yes A' &@CRLF)
            MsgBox(64, 'Result', 'Key А - USB')
        EndIf
     EndIf

    Return 1
    Return $GUI_RUNDEFMSG ;Pass on to default winproc
EndFunc   ;==>WM_INPUT

Func EnumRawKeyboards($sDeviceNameMatch = "")
    ;Returns array of keyboard device IDs
    Local $tInfo, $aData = _WinAPI_EnumRawInputDevices()

    If IsArray($aData) Then
        Local $aKeyboards[$aData[0][0] + 1][4]

        ;'dword Size;dword Type;';'struct;dword KbType;dword KbSubType;dword KeyboardMode;dword NumberOfFunctionKeys;dword NumberOfIndicators;dword NumberOfKeysTotal;endstruc'
        Local $_tagRID_INFO_KEYBOARD = $tagRID_INFO_KEYBOARD

        If StringRight($_tagRID_INFO_KEYBOARD, 1) <> "t" Then $_tagRID_INFO_KEYBOARD &= "t" ; t is missing from endstruct

        Local $iCt = 0, $iSz
        Local $tInfo, $tDeviceName, $sDeviceName

        For $i = 1 To $aData[0][0]
            $tInfo = DllStructCreate($_tagRID_INFO_KEYBOARD)

            If _WinAPI_GetRawInputDeviceInfo($aData[$i][0], $tInfo, DllStructGetSize($tInfo), $RIDI_DEVICEINFO) And $aData[$i][1] = $RIM_TYPEKEYBOARD Then
                $iSz = _WinAPI_GetRawInputDeviceInfo($aData[$i][0], 0, 0, $RIDI_DEVICENAME) ;Get bytes needed
                $tDeviceName = DllStructCreate('wchar[' & $iSz + 1 & ']') ;Holds device name string

                If _WinAPI_GetRawInputDeviceInfo($aData[$i][0], $tDeviceName, DllStructGetSize($tDeviceName), $RIDI_DEVICENAME) Then
                    $sDeviceName = DllStructGetData($tDeviceName, 1)

                    If $sDeviceNameMatch <> "" And Not StringInStr($sDeviceName, $sDeviceNameMatch) Then ContinueLoop

                    $iCt += 1
                    $aKeyboards[$iCt][0] = $aData[$i][0] ;Handle
                    $aKeyboards[$iCt][1] = $aData[$i][1] ;Type
                    $aKeyboards[$iCt][2] = $sDeviceName
                    $aKeyboards[$iCt][3] = DllStructGetData($tInfo, "NumberOfKeysTotal")
                    Global $HandleX = $aData[1][0]

                EndIf

            EndIf
        Next
        $aKeyboards[0][0] = $iCt ; Write count of keyboard devices to array
        ReDim $aKeyboards[$iCt + 1][4] ;Resize array
    EndIf
    Return $aKeyboards
 EndFunc   ;==>EnumRawKeyboards

 

Link to comment
Share on other sites

Ah yes, i see what you did there.

 

Edited by careca
Spoiler

Renamer - Rename files and folders, remove portions of text from the filename etc.

GPO Tool - Export/Import Group policy settings.

MirrorDir - Synchronize/Backup/Mirror Folders

BeatsPlayer - Music player.

Params Tool - Right click an exe to see it's parameters or execute them.

String Trigger - Triggers pasting text or applications or internet links on specific strings.

Inconspicuous - Hide files in plain sight, not fully encrypted.

Regedit Control - Registry browsing history, quickly jump into any saved key.

Time4Shutdown - Write the time for shutdown in minutes.

Power Profiles Tool - Set a profile as active, delete, duplicate, export and import.

Finished Task Shutdown - Shuts down pc when specified window/Wndl/process closes.

NetworkSpeedShutdown - Shuts down pc if download speed goes under "X" Kb/s.

IUIAutomation - Topic with framework and examples

Au3Record.exe

Link to comment
Share on other sites

In order to block the key presses it starts getting complicated

I made a hooking DLL in FASM assembly that worked decently but not perfectly I don't remember exactly where I was in this code so don't expect too much

Spoiler
; FASM Second Keyboard Hook BILGUS 2018 -> RawInput64.dll

format PE64 GUI 5.0 DLL 
entry DllEntryPoint

;Includes
include 'win64a.inc'
        ;Don't Forget to set include directory
        ;in FASMW.ini otherwise this needs to be a realtive path..

;Constants
    ;Internal Constants
    KE_INTERNAL     = 0xFEED
    KE_SPECIAL      = KE_INTERNAL
    KE_PRESSED      = 0x8000
    VK_WIN          = 0xFF
    ;User32 Constants
    HWND_MESSAGE    = 0;(-3) ;create a message-only window when set as Parent
    RIDEV_INPUTSINK = 0x00000100
    RIDEV_NOLEGACY  = 0x00000030
    RIDEV_REMOVE    = 0x00000001
    
    RID_INPUT  = 0x10000003
    RID_HEADER = 0x10000005
    
    RI_KEY_MAKE  = 0x0000
    RI_KEY_BREAK = 0x0001
    RI_KEY_E0    = 0x0002
    RI_KEY_E1    = 0x0004

    KEYEVENTF_EXTENDEDKEY = 0x0001
    KEYEVENTF_KEYUP       = 0x0002
    KEYEVENTF_UNICODE     = 0x0004
    KEYEVENTF_SCANCODE    = 0x0008

    WM_INPUT = 0x00FF

;Macros
    macro return arg
    {
        mov     rax, arg
        ret
    } ;return arg => rax

    macro deref reg, pointer
    {
       push pointer
       pop reg
    } ;dereference pointer =>register

;Structs
    ;RAWINPUT STRUCTS
    struct RAWINPUTDEVICE
            usUsagePage du  ?
            usUsage     du  ?
            dwFlags     dd  ?
            hWndTarget  dq  ?
    ends ; RAWINPUTDEVICE

    struct RAWINPUTHEADER
        dwType      dd  ?
        dwSize      dd  ?
        hDevice     dq  ?
        wParam      dq  ?
    ends ; RAWINPUTHEADER
    
    struct RAWMOUSE
        usFlags             dw  ?
        union
            ulButtons       dd  ?
            struct
                usButtonFlags   dw  ?
                usButtonData    dw  ?
            ends
        ends ; union
        ulRawButtons        dd  ?
        lLastX              dd  ?
        lLastY              dd  ?
        ulExtraInformation  dd  ?
    ends ; RAWMOUSE
    
    struct RAWKEYBOARD
        MakeCode            du  ?
        Flags               du  ?
        Reserved            du  ?
        VKey                du  ?
        Message             dd  ?
        ExtraInformation    dq  ?
    ends ; RAWKEYBOARD
    
    struct RAWHID 
        dwSizeHid           dd  ?
        dwCount             dd  ?
        bRawData            db 1 dup(?)
    ends ; RAWHID
       
    struct RAWINPUT
        header  RAWINPUTHEADER
        union ;data
            mouse           RAWMOUSE
            keyboard        RAWKEYBOARD
            hid             RAWHID
        ends ; union ; data
    ends ; RAWINPUT

    ;SetWindowsHookExA STRUCTS
    struct KBDLLHOOKSTRUCT
        vkCode      dd  ?
        scanCode    dd  ?
        flags       dd  ?
        time        dd  ?
        dwExtraInfo dq  ?
    ends ; KBDLLHOOKSTRUCT

    ;INTERNAL STRUCTS
    struct REGDEVICE
        align     8;
        hWnd      dq  ?
        hDevice   dq  ?
        pCallback dq  ?
        iMsg      dd  ?
    ends ; REGDEVICE
    
    struct SPECIALKEYSSTATE
        bLSHIFT    du ?
        bRSHIFT    du ?
        bCONTROL   du ?
        bMENU      du ?
    ends ; SPECIALKEYSSTATE

section '.data' data readable writeable
;Initialized data
    ;Handles
    hInst           dq 0
    hWnd_Msg        dq 0
    hTimer          dq 0
    
    ;Structs
    _sksKeyState    SPECIALKEYSSTATE 0, 0, 0, 0
    _wcexRI         WNDCLASSEX  \
             sizeof.WNDCLASSEX, \
                             0, \
                    WindowProc, \
                             0, \
                             0, \
                          NULL, \
                          NULL, \
                          NULL, \
                          NULL, \
                          NULL, \
                        _class, \
                          NULL
    ;Strings
    _msg MSG
    _kbstate      rb 256
    _buffer       rb 255 ; ShowErrorMessage
    _title        db 'RawInput Message Window', 0
    _class        db 'RAW_INPUT_64', 0
    _init_error   db 'Raw Input initialization failed 0x%x', 0
    _reg_error    db 'Raw Input Device registration failed %d', 0
    _hook_error   db 'Raw Input Error failed to install hook 0x%x', 0
    _unhook_error db 'Raw Input Error failed to remove hook', 0
    _raw_error    db 'Raw Input Error', 0

section '.bss' data readable writeable
;Non-Initialized data
    hinstance           dq ?
    hKeyHook            dq ?

    _regdevice          REGDEVICE

    align 8 ;Important for WOW64
    _ridevice           RAWINPUTDEVICE
    align 8 ;Important for WOW64
    _ridata             RAWINPUT

section '.text' code readable executable

    proc DllEntryPoint hinstDLL, fdwReason, lpvReserved
        ;Preserve registers
        mov     [hInst], rcx
        mov     [fdwReason], rdx
        ;mov     [lpvReserved], r8

        irps reason, PROCESS_DETACH PROCESS_ATTACH THREAD_DETACH THREAD_ATTACH
        {
                cmp [fdwReason], DLL_#reason
                je .#reason
        }

        jmp     .finish
        
        .THREAD_DETACH:
            ;fastcall ShowMessage, 0, "Thread", "detach", MB_OK
            jmp        .finish
            
        .THREAD_ATTACH:
            ;fastcall ShowMessage, 0, "Thread", "attach", MB_OK
            jmp        .finish

        .PROCESS_DETACH:
            fastcall Cleanup
            ;fastcall ShowMessage, 0, "Process", "detach", MB_OK
            ;invoke  ExitProcess,0
            jmp     .finish

        .PROCESS_ATTACH:
            ;fastcall ShowMessage, 0, "Process", "attach", MB_OK
            jmp     .finish

        .finish:
            return TRUE

        .failure:
            return FALSE

    endp ; DllEntryPoint

    proc Cleanup
        mov [_regdevice.pCallback], 0
        fastcall RegisterRawInput, 0, 0x1, 0x6, RIDEV_REMOVE
        fastcall Special_Key_State, -1 ;unSet invalid keyboard state
        invoke DestroyWindow, [hWnd_Msg]

        ret
    endp ; Cleanup

    proc RegisterRawInput hWnd, Usagepage, Usage, Flags
        mov     [_ridevice.hWndTarget], qword rcx   ; window that recieves wm_input
        mov     [_ridevice.usUsagePage], word dx    ;
        mov     [_ridevice.usUsage],     word r8w   ;
        mov     [_ridevice.dwFlags],    dword r9d   ;
        
        invoke  RegisterRawInputDevices, addr _ridevice, 1, sizeof.RAWINPUTDEVICE
        cmp rax, FALSE
        je .error_register
        ret
        .error_register:
            invoke  GetLastError
            fastcall ShowErrorMessage, [_regdevice.hWnd], _init_error, rax
    endp ; RegisterRawInput

    proc Register_Keyboard, _RegDev, pRegDevice
        mov r8, 0 ;Which parameter? (internal error)
        or  rcx, rcx ;_RegDev
        jz  .regkb_err
        or  rdx, rdx ;pRegDevice
        jz  .regkb_err

        mov [_RegDev], rcx
        mov [pRegDevice], rdx

        deref rax, [pRegDevice]
        mov r8, 1  ;Which parameter? (external error)
        irps field, hDevice pCallback ;iterate over each field of struct check value
        {
            add r8, 1 ;Which parameter?  (external error)
            cmp [rax+REGDEVICE.#field], 0x0
            je .regkb_err
        }

        ;make an internal copy of Regdevice
        invoke RtlMoveMemory,[_RegDev],[pRegDevice], sizeof.REGDEVICE

        return 1

        .regkb_err:
            fastcall ShowErrorMessage, 0, _reg_error, r8
            return 0
    endp ; Register_Keyboard

    proc Unhook_Keyboard ;EXPORTED FUNCTION
        fastcall Cleanup
        return 1
    endp ; Unhook_Keyboard

    proc Init_Keyboard, pRegDevice ;EXPORTED FUNCTION
        mov     [pRegDevice], rcx ;[hWnd,hDevice,pCallback];

        fastcall Register_Keyboard, _regdevice, [pRegDevice]
        or      rax, rax
        jz      .init_quit

        mov     rax, [hInst]
        mov     [_wcexRI.hInstance], rax
        invoke  RegisterClassEx, _wcexRI
        test    rax, rax
        jz      .init_error

        invoke  CreateWindowEx, 0, _class, _title, WS_POPUP+WS_VISIBLE, 0, 0, 0, 0, HWND_MESSAGE, NULL, [hInst], NULL
        test    rax, rax
        jz      .init_error
        mov     [hWnd_Msg], rax

        fastcall RegisterRawInput, [hWnd_Msg], 0x1, 0x6, RIDEV_INPUTSINK
        test    rax, rax
        jz      .init_error

        fastcall Init_KeyHook
        test    rax, rax
        jz      .init_error
        
        return [hWnd_Msg] ;return hWnd of message window

        .init_error:
            invoke  GetLastError
            fastcall ShowErrorMessage, [_regdevice.hWnd], _init_error, rax
            fastcall Cleanup
        .init_quit:
            return 0
    endp ; Init_Keyboard
   
    proc Init_KeyHook
        invoke SetWindowsHookEx, WH_KEYBOARD_LL, KeyEvent, [hInst], NULL
        cmp rax, 0
        je .hookerror

        mov [hKeyHook], rax
        ret

        .hookerror:
            return 0
    endp ; Init_KeyHook
    
    proc KeyEvent nCode, wParam, lParam
        local wMsg:DWORD

        ;Preserve Registers
        mov     [nCode],  rcx
        mov     [wParam], rdx
        mov     [lParam], r8

        cmp     [_regdevice.pCallback], 0
        je      nexthook

        cmp     [nCode],  HC_ACTION
        jne     nexthook

        mov r8, [lParam]
        virtual at r8
            kbHook KBDLLHOOKSTRUCT <>
        end virtual

        mov rcx, [kbHook.dwExtraInfo]
        ;This event was injected by Parse_Raw_Input
        cmp rcx, KE_INTERNAL
        je  nexthook

        irps wparam, WM_KEYDOWN WM_SYSKEYDOWN
        {
            cmp   [wParam], wparam
            je    keydown
        }
        jmp keyup
        
        keydown:
            ;Pass Special keys
            mov ecx, [kbHook.vkCode]
            cmp ecx, VK_TAB
            je nexthook

            ;Checks KEY
            irps vkc, LSHIFT RSHIFT
            {
                cmp ecx, VK_#vkc
                jne .skipdn#vkc
                mov [_sksKeyState.b#vkc], KE_PRESSED ;save the state
                jmp nexthook
                .skipdn#vkc:
            }
            
            ;Checks KEY, LKEY, RKEY
            irps vkc, CONTROL MENU
            {
                cmp ecx, VK_#vkc
                je .setpressed#vkc
                cmp ecx, VK_L#vkc
                je .setpressed#vkc
                cmp ecx, VK_R#vkc
                jne .skipset#vkc
                .setpressed#vkc:
                    mov [_sksKeyState.b#vkc], KE_PRESSED ;save the state
                .skipset#vkc:
            }

            .block:
                invoke SetTimer, [hWnd_Msg], [hTimer], 250, NULL
                mov [hTimer], rax
                ;Set an invalid keyboard state till we can decide what to do with the key
                ;fastcall Special_Key_State, 1
                fastcall AttachThread
                jmp      nexthook

        keyup:
            ;Pass Special keys
            mov ecx, [kbHook.vkCode]
            cmp ecx, VK_TAB
            je nexthook
            
            irps vkc, LSHIFT RSHIFT
            {
                cmp ecx, VK_#vkc
                jne .skipup#vkc
                mov [_sksKeyState.b#vkc], 0x0 ;clear the state
                jmp nexthook
                .skipup#vkc:
            }  

            irps vkc, CONTROL MENU
            {
                cmp ecx, VK_#vkc
                je .clearpressed#vkc
                cmp ecx, VK_L#vkc
                je .clearpressed#vkc
                cmp ecx, VK_R#vkc
                jne .skipclear#vkc
                .clearpressed#vkc:
                    mov [_sksKeyState.b#vkc], 0x0 ;clear the state
                .skipclear#vkc:
            }

        nexthook:
            invoke CallNextHookEx, [hKeyHook], [nCode], [wParam], [lParam]
            ret
    endp ; KeyEvent

    proc Special_Key_State bSet
        return 0;
        mov [bSet], rcx
        cmp rcx, 0
        jg .setstate

        .clrstate: ;<= 0
            invoke SetTimer, [hWnd_Msg], [hTimer], 0x7FFFFFFF, NULL
            ;Clears an Invalid keyboard state (Except keys user pressed)
            irps ikey, CONTROL MENU RSHIFT LSHIFT;
            {
                ;invoke GetAsyncKeyState, VK_#ikey

                ;and rax, KE_PRESSED
                ;jz .skip_clear#ikey ;Already unset

                cmp [bSet], 0
                jl .clear#ikey

                and [_sksKeyState.b#ikey], KE_PRESSED
                jnz .skip_clear#ikey ;
                .clear#ikey:
                    mov [_sksKeyState.b#ikey], 0x0
                    invoke keybd_event,VK_#ikey , 0, KEYEVENTF_KEYUP, KE_SPECIAL
                    ;fastcall Send_Input_Kb, VK_#ikey, 0, KEYEVENTF_KEYUP, KE_SPECIAL
                .skip_clear#ikey:
            }
            ret
        .setstate: ; > 0
            ;Sets an Invalid keyboard state (Ctrl Alt LShift Rshift pressed)
            irps ikey,  CONTROL MENU LSHIFT RSHIFT;
            {
                ;invoke GetAsyncKeyState, VK_#ikey
                ;and rax, KE_PRESSED
                and [_sksKeyState.b#ikey], KE_PRESSED
                jnz .skip_set#ikey ;Already set

                invoke keybd_event,VK_#ikey , 0, 0, KE_SPECIAL
                ;fastcall Send_Input_Kb, VK_#ikey, 0, 0, KE_SPECIAL
                .skip_set#ikey:
            }
            ret
    endp ; Special_Key_State

    proc Parse_Raw_Input lParam
        local uiSize:DWORD
        local dwFlags:DWORD
        
        mov     [lParam], rcx

        cmp [_regdevice.pCallback], 0
        je       .err_ovfl

        invoke  GetRawInputData, [lParam], RID_INPUT, NULL, addr uiSize, sizeof.RAWINPUTHEADER
        mov     eax, dword [uiSize]
        cmp     eax, sizeof.RAWINPUT
        jg      .err_ovfl

        invoke  GetRawInputData, [lParam], RID_INPUT, addr _ridata, addr uiSize, sizeof.RAWINPUTHEADER

        ;We sent this key.. Ignore it
        cmp [_ridata.keyboard.ExtraInformation], KE_INTERNAL
        je  .finished

        mov rcx, [_ridata.header.hDevice]
        
        ;Filtered Device?
        cmp rcx, [_regdevice.hDevice]
        jne .unfiltered

        .filtered:
            and [_ridata.keyboard.Flags], RI_KEY_BREAK ;Key Up
            jnz .callback
            
            fastcall Special_Key_State, 0 ;unSet invalid keyboard state
            .callback:
                cmp [_regdevice.pCallback], 0
                je       .err_ovfl
                deref    rax, [_regdevice.pCallback]
                ccall    rax, [_ridata.header.hDevice], [_ridata.keyboard.VKey], [_ridata.keyboard.MakeCode], [_ridata.keyboard.Flags]
                jmp      .finished

        .unfiltered:
            and [_ridata.keyboard.Flags], RI_KEY_BREAK ;Key Up
            jnz .finished
            
            mov [dwFlags], 0
            
            cmp [_ridata.keyboard.VKey], VK_PRIOR
            jl .scancode
            cmp [_ridata.keyboard.VKey], VK_HELP
            jg .scancode
            jmp .sendkey
            
            .scancode:
                mov [dwFlags], KEYEVENTF_SCANCODE
                and [_ridata.keyboard.Flags], RI_KEY_E0 ;Extended Key
                jz .notextended0
                add [dwFlags], KEYEVENTF_EXTENDEDKEY
                jmp .sendkey

            .notextended0:
                and [_ridata.keyboard.Flags], RI_KEY_E1 ;Extended Key
                jz .sendkey
                add [dwFlags], KEYEVENTF_EXTENDEDKEY
                
            .sendkey:
                fastcall Special_Key_State, 0 ;unSet invalid keyboard state
                invoke   keybd_event,[_ridata.keyboard.VKey] , [_ridata.keyboard.MakeCode], [dwFlags], KE_INTERNAL
                cmp rax, 1
                jl .err_send
                jmp      .finished
                
        .err_send:
            invoke  GetLastError
            fastcall ShowErrorMessage, [_regdevice.hWnd], "err %d", rax
            return 0
        .err_ovfl:
            fastcall Special_Key_State, -1 ;unSet invalid keyboard state
            fastcall ShowErrorMessage, [_regdevice.hWnd], _raw_error, 0
            return 0

        .finished:
            return 1
    endp ; Parse_Raw_Input
    
;Window Callbacks -------------------------------------------------------------------------------------
    proc WindowProc hWnd, wMsg, wParam, lParam

        ;Check for Window Messages we would like to handle
        irps wmsg,  WM_INPUT WM_CREATE WM_DESTROY WM_TIMER WM_KEYDOWN WM_CHAR
        {
            cmp edx, wmsg
            je .#wmsg
        }

        .defwindowproc:
            invoke DefWindowProc, rcx, rdx, r8, r9
            jmp    .finish
        .WM_TIMER:
            fastcall Special_Key_State, 0
            return 0
        .WM_CHAR:
        .WM_KEYDOWN:
            fastcall ShowErrorMessage, 0, "KD", 0
            return 0;
        .WM_INPUT:
            fastcall WM_INPUT_Proc, rcx, rdx, r8, r9
            or      rax, rax
            jnz     .defwindowproc ;let DefWndProc cleanup
            jmp     .finish
            
        .WM_CREATE:
            ;callback on startup
            deref   rax, [_regdevice.pCallback]
            ccall   rax, [_regdevice.hDevice], 0, 0, 0
            xor     rax, rax
            jmp     .finish

        .WM_DESTROY:
            invoke KillTimer, [hWnd_Msg], [hTimer]
            invoke UnhookWindowsHookEx, [hKeyHook]
            cmp rax, 0
            jnz .next
            fastcall ShowErrorMessage, 0, _unhook_error, 0
            .next:
            ;invoke PostQuitMessage, NULL
            return 0

        .finish:
            ret
        
    endp ; WindowProc
    
    proc WM_INPUT_Proc hWnd, wMsg, wParam, lParam
        fastcall Parse_Raw_Input, r9 ;(lParam)
        ret
    endp ; WM_INPUT_Proc
;------------------------------------------------------------------------
    proc AttachThread
        local gm:QWORD
        ;local msg:MSG
        local IdCurrentThread:QWORD
        local hActiveWindow:QWORD
        local hActiveProcessID:QWORD
        local IdActiveThread:QWORD
        ;invoke GetKeyboardState, [_kbstate]
        invoke GetWindowThreadProcessId, [hWnd_Msg], NULL
        mov [IdCurrentThread], rax

        invoke GetForegroundWindow
        mov [hActiveWindow], rax

        invoke GetWindowThreadProcessId, [hActiveWindow], NULL
        mov [IdActiveThread], rax

        cmp rax, [IdCurrentThread]
        je .done

        .attach:
        invoke AttachThreadInput, [IdActiveThread], [IdCurrentThread], TRUE
        cmp rax, 0
        jne .detach
        fastcall ShowErrorMessage, 0, "attach %d", rax
        return 0

        .detach:
        ;rept 255 count
        ;{
        ;    mov [_kbstate + (8 * count)], 0x0
        ;}
        .getmsg:
        invoke PeekMessage, _msg, NULL, 0, 0, 0
        mov [gm], rax
        cmp [_msg.message], 0
        je .getmsg
        cmp [_msg.message], 255
        je .getmsg
        cmp [_msg.message], 160
        je .getmsg
        cmp [_msg.message], 275
        je .getmsg
        cmp [_msg.message], 512
        je .getmsg
        fastcall ShowErrorMessage, 0, "msg %d", [_msg.message]
        ;invoke TranslateMessage, _msg
        ;invoke DispatchMessage, _msg
        pause
        cmp [gm], 0
        je .getmsg
        ;invoke SetKeyboardState, [_kbstate]
       ; invoke AttachThreadInput, [IdActiveThread], [IdCurrentThread], FALSE
        cmp rax, 0
        jne .done
        fastcall ShowErrorMessage, 0, "detach %d", rax
        return 0

        .cancel:
        fastcall ShowErrorMessage, 0, "cancel %d", rax

        .done:

        return 0
        ;uint activeProcess;
        ;uint activeThread = Win32.GetWindowThreadProcessId(activeWindow, out activeProcess);

        ; uint windowProcess;
        ;uint windowThread = Win32.GetWindowThreadProcessId(window, out windowProcess);

        ;if (currentThread != activeThread)
        ;Win32.AttachThreadInput(currentThread, activeThread, true);
        ;if (windowThread != currentThread)
        ;Win32.AttachThreadInput(windowThread, currentThread, true);
    endp
    proc ShowErrorMessage hWnd, sMsg, iVal
        ;Preserve registers
        mov     [hWnd], rcx
        mov     [sMsg], rdx
        mov     [iVal], r8

        cinvoke wsprintf, _buffer, [sMsg], [iVal]

        ;invoke  MessageBox, [hWnd], _buffer, NULL, MB_ICONERROR+MB_OK
        fastcall ShowMessage, [hWnd], "Error", _buffer, MB_ICONERROR+MB_OK

        ret 
    endp ; ShowErrorMessage

    proc ShowMessage hWnd, sTitle, sMsg, uType
            ;Preserve registers
            mov     [hWnd], rcx
            mov     [sTitle], rdx
            mov     [sMsg], r8
            mov     [uType], r9

            invoke  MessageBox, [hWnd], [sMsg], [sTitle], [uType]
            ret
    endp ; ShowMessage

section '.idata' import data readable writeable

    library kernel_32, 'KERNEL32.DLL', \
              user_32,  'USER32.DLL';, \
        ;kernel32, 'KERNEL32.DLL', \
        ;user32, 'USER32.DLL'

    ;TMP Imports whole library..
    ;include 'api\kernel32.inc'
    ;include 'api\user32.inc'
    ;TMP
    
    import kernel_32, \
        ExitProcess,             'ExitProcess', \
        GetCurrentThreadId,      'GetCurrentThreadId', \
        GetLastError,            'GetLastError', \
        RtlMoveMemory,           'RtlMoveMemory'


    import user_32, \
        AttachThreadInput,       'AttachThreadInput', \
        CallNextHookEx,          'CallNextHookEx', \
        CreateWindowEx,          'CreateWindowExA', \
        DefWindowProc,           'DefWindowProcA', \
        DestroyWindow,           'DestroyWindow', \
        DispatchMessage,         'DispatchMessageA', \
        GetAsyncKeyState,        'GetAsyncKeyState', \
        GetForegroundWindow,     'GetForegroundWindow', \
        GetKeyboardState,        'GetKeyboardState', \
        GetMessage,              'GetMessageA', \
        GetRawInputData,         'GetRawInputData', \ ; Not in the FASM includes
        GetWindowThreadProcessId,'GetWindowThreadProcessId', \
        keybd_event,             'keybd_event', \
        KillTimer,               'KillTimer', \
        MessageBox,              'MessageBoxA', \
        PeekMessage,            'PeekMessageA', \
        PostQuitMessage,         'PostQuitMessage', \
        RegisterClassEx,         'RegisterClassExA', \
        RegisterRawInputDevices, 'RegisterRawInputDevices', \  ; Not in the FASM includes
        SetKeyboardState,        'SetKeyboardState', \
        SetTimer,                'SetTimer', \
        SetWindowsHookEx,        'SetWindowsHookExA', \
        TranslateMessage,        'TranslateMessage', \
        UnhookWindowsHookEx,     'UnhookWindowsHookEx', \
        wsprintf,                'wsprintfA'
        ;SendInput,               'SendInput', \

section '.edata' export data readable 

    export 'RAWINPUT64.DLL', \ 
        Init_Keyboard,     'Init_Keyboard', \
        Unhook_Keyboard,   'Unhook_Keyboard'
section '.reloc' fixups data readable discardable

    if $=$$
        dd 0, 8              ; if there are no fixups, generate dummy entry
    end if

 

Then Autoit side:

;Bilgus 2018
;Second Keyboard Hook Example
;Requires RawInput64.dll
;Hooked keyboard will be blocked to all other programs till exit
#AutoIt3Wrapper_UseX64=Y ;ONLY 64 BIT

#include <WinAPISys.au3>

#include <GUIConstantsEx.au3>
#include <ComboConstants.au3>

#include <GuiEdit.au3>
#include <ScrollBarsConstants.au3>

Global $ghSelectedDevice, $ghCallback, $ghDll = 0

Global $gaKeyboards = EnumRawKeyboards("\HID")
Global $gsKeyboards, $giSelected

Global $gh_Form1 = GUICreate("Keyboard Filtering", 800, 200)
Global $gid_ComboKb = GUICtrlCreateCombo("Select Keyboard", 16, 8, 770, 25, BitOR($CBS_DROPDOWN, $CBS_AUTOHSCROLL))
Global $gid_Hook = GUICtrlCreateButton("Hook", 16, 40, 73, 25)
Global $gid_Unhook = GUICtrlCreateButton("UnHook", 100, 40, 73, 25)
Global $gid_Edit1 = GUICtrlCreateEdit("", 16, 70, 770, 100)
GUICtrlSetState($gid_Unhook, $GUI_DISABLE)
GUISetState(@SW_SHOW)

If IsArray($gaKeyboards) And $gaKeyboards[0][0] >= 1 Then
    For $i = 1 To $gaKeyboards[0][0]
        $gsKeyboards &= $i & ". " & $gaKeyboards[$i][2] & "|"
    Next
EndIf

GUICtrlSetData($gid_ComboKb, $gsKeyboards)

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit

        Case $gid_Hook
            $giSelected = Int(StringLeft(GUICtrlRead($gid_ComboKb), 2))

            If $giSelected < 1 Then
                MsgBox(0, "Error", "You must select a device..")
                ContinueLoop
            EndIf

            GUICtrlSetState($gid_Hook, $GUI_DISABLE)
            $ghSelectedDevice = $gaKeyboards[$giSelected][0]
            ConsoleWrite("Selected Device: " & $ghSelectedDevice & @CRLF)

            ;Open Dll get a handle
            If Not $ghDll Then
                $ghDll = DllOpen(@ScriptDir & "\RawInput.DLL")
                ConsoleWrite("Opening " & @ScriptDir & "\RawInput.DLL " & ($ghDll = 0 ? "Failed" : "Success"))
            EndIf

            $ghCallback = DllCallbackRegister(_Callback, "none", "handle;int;ushort;ushort")
            HookKeyboard($ghDll, $gh_Form1, $ghSelectedDevice, $ghCallback)
            GUICtrlSetState($gid_Unhook, $GUI_ENABLE)

        Case $gid_Unhook
            ConsoleWrite("Unhook" & @CRLF)
            DllCall($ghDll, "int", 'Unhook_Keyboard')
            ; Delete callback function.
            DllCallbackFree($ghCallback)
            $ghCallback = 0
            GUICtrlSetState($gid_Unhook, $GUI_DISABLE)
            GUICtrlSetState($gid_Hook, $GUI_ENABLE)
    EndSwitch
WEnd

Func _Exit()
    Exit
EndFunc   ;==>_Exit

Func EnumRawKeyboards($sDeviceNameMatch = "")
    ;Returns array of keyboard device IDs
    Local $tInfo, $aData = _WinAPI_EnumRawInputDevices()

    If IsArray($aData) Then
        Local $aKeyboards[$aData[0][0] + 1][4]

        ;'dword Size;dword Type;';'struct;dword KbType;dword KbSubType;dword KeyboardMode;dword NumberOfFunctionKeys;dword NumberOfIndicators;dword NumberOfKeysTotal;endstruc'
        Local $_tagRID_INFO_KEYBOARD = $tagRID_INFO_KEYBOARD

        If StringRight($_tagRID_INFO_KEYBOARD, 1) <> "t" Then $_tagRID_INFO_KEYBOARD &= "t" ; t is missing from endstruct

        Local $iCt = 0, $iSz
        Local $tInfo, $tDeviceName, $sDeviceName

        For $i = 1 To $aData[0][0]
            $tInfo = DllStructCreate($_tagRID_INFO_KEYBOARD)

            If _WinAPI_GetRawInputDeviceInfo($aData[$i][0], $tInfo, DllStructGetSize($tInfo), $RIDI_DEVICEINFO) And $aData[$i][1] = $RIM_TYPEKEYBOARD Then
                $iSz = _WinAPI_GetRawInputDeviceInfo($aData[$i][0], 0, 0, $RIDI_DEVICENAME) ;Get bytes needed
                $tDeviceName = DllStructCreate('wchar[' & $iSz + 1 & ']') ;Holds device name string

                If _WinAPI_GetRawInputDeviceInfo($aData[$i][0], $tDeviceName, DllStructGetSize($tDeviceName), $RIDI_DEVICENAME) Then
                    $sDeviceName = DllStructGetData($tDeviceName, 1)

                    If $sDeviceNameMatch <> "" And Not StringInStr($sDeviceName, $sDeviceNameMatch) Then ContinueLoop

                    $iCt += 1
                    $aKeyboards[$iCt][0] = $aData[$i][0] ;Handle
                    $aKeyboards[$iCt][1] = $aData[$i][1] ;Type
                    $aKeyboards[$iCt][2] = $sDeviceName
                    $aKeyboards[$iCt][3] = DllStructGetData($tInfo, "NumberOfKeysTotal")
                EndIf
            EndIf
        Next
        $aKeyboards[0][0] = $iCt ; Write count of keyboard devices to array
        ReDim $aKeyboards[$iCt + 1][4] ;Resize array
    EndIf
    Return $aKeyboards
EndFunc   ;==>EnumRawKeyboards

Func _Callback($hDevice, $iVKey, $iMakeCode, $iFlags)
    ;We recieve key events for our hooked keyboard here nothing else does..
    Local $sKeyData = ""
    $sKeyData &= "hDevice: " & $hDevice & " "
    $sKeyData &= "iVKey: " & Hex($iVKey, 2) & " "
    $sKeyData &= "$iMakeCode: " & $iMakeCode & " "
    $sKeyData &= "$iFlags: " & $iFlags & @CRLF
    GUICtrlSetData($gid_Edit1, _GUICtrlEdit_GetText($gid_Edit1) & $sKeyData)
    _GUICtrlEdit_Scroll($gid_Edit1, $SB_SCROLLCARET)
    Return 0
EndFunc   ;==>_Callback

Func HookKeyboard($hDll, $hWnd, $hDevice, $hCallback)
    ;Set up the device we would like to hook
    Local $tRegDevice = DllStructCreate("hwnd hWnd;handle hDevice;PTR pCallback")
    DllStructSetData($tRegDevice, 'hWnd', $hWnd) ;This can be 0
    DllStructSetData($tRegDevice, 'hDevice', $hDevice) ;This must be a valid device handle
    DllStructSetData($tRegDevice, 'pCallback', DllCallbackGetPtr($hCallback)) ;callback function

    ;Call the already opened dll, It must stay open for the duration
    Local $aDll = DllCall($hDll, "hwnd", 'Init_Keyboard', "ptr", DllStructGetPtr($tRegDevice))
    If IsArray($aDll) Then
        ConsoleWrite("Msg hWnd:" & $aDll[0] & @CRLF) ;Returns the hWnd of the invisible message window from dll
    Else
        ConsoleWrite("Failure" & @CRLF)
    EndIf
    Return
EndFunc   ;==>HookKeyboard


 

 

 

The problem is that you need to delay keypresses until the device is known and windows registers a keypress prior to filling the info in GetRawInputData

this makes it unsuitable imo.

 

Next I tried my own low level keyboard driver but then you need to turn test signing on to use it.

I tried a keyboard driver that is specifically made for this called Interception

http://www.oblita.com/interception.html

I really like the idea but dislike the lack of source code but this is probably your best bet

Edit: Looks like there is source code:

https://github.com/oblitum/Interception/tree/master/library

 

Edited by Bilgus
Link to comment
Share on other sites

Did you try modifying argumentum's code? or the code i posted with your keyboard handle? ;)

EDIT: Removed

Edited by careca
Spoiler

Renamer - Rename files and folders, remove portions of text from the filename etc.

GPO Tool - Export/Import Group policy settings.

MirrorDir - Synchronize/Backup/Mirror Folders

BeatsPlayer - Music player.

Params Tool - Right click an exe to see it's parameters or execute them.

String Trigger - Triggers pasting text or applications or internet links on specific strings.

Inconspicuous - Hide files in plain sight, not fully encrypted.

Regedit Control - Registry browsing history, quickly jump into any saved key.

Time4Shutdown - Write the time for shutdown in minutes.

Power Profiles Tool - Set a profile as active, delete, duplicate, export and import.

Finished Task Shutdown - Shuts down pc when specified window/Wndl/process closes.

NetworkSpeedShutdown - Shuts down pc if download speed goes under "X" Kb/s.

IUIAutomation - Topic with framework and examples

Au3Record.exe

Link to comment
Share on other sites

  • Moderators

Hi,

Last warning - I have just had to delete yet another "keylogger" code example from this thread. Remember the restrictions set out by Jon: "checking for a few keys" is fine - "looking for the whole keyboard" most definitely is not.

As it seems most people posting here are trying hard to keep within those bounds I am letting the thread run for the moment, but one more transgression and I will be forced to close it - and deal with whoever cannot understand the simple rules that apply.

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...