Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 9개 있습니다.)
Windows: 148. Windows - Raw Input의 Top level collection 의미
; https://www.sysnet.pe.kr/2/0/11612

.NET Framework: 788. RawInput을 이용한 키보드/마우스 입력 모니터링
; https://www.sysnet.pe.kr/2/0/11615

개발 환경 구성: 488. (User-mode 코드로 가상 USB 장치를 만들 수 있는) USB/IP PROJECT 소개
; https://www.sysnet.pe.kr/2/0/12213

개발 환경 구성: 490. C# - (Wireshark의) USBPcap을 이용한 USB 패킷 모니터링
; https://www.sysnet.pe.kr/2/0/12215

.NET Framework: 904. USB/IP PROJECT를 이용해 C#으로 USB Keyboard 가상 장치 만들기
; https://www.sysnet.pe.kr/2/0/12216

.NET Framework: 905. C# - DirectX 게임 클라이언트 실행 중 키보드 입력을 감지하는 방법
; https://www.sysnet.pe.kr/2/0/12218

.NET Framework: 917. C# - USB 관련 ETW(Event Tracing for Windows)를 이용한 키보드 입력을 감지하는 방법
; https://www.sysnet.pe.kr/2/0/12246

.NET Framework: 990. C# - SendInput Win32 API를 이용한 가상 키보드/마우스
; https://www.sysnet.pe.kr/2/0/12469

개발 환경 구성: 607. 로컬의 USB 장치를 원격 머신에 제공하는 방법 - usbip-win
; https://www.sysnet.pe.kr/2/0/12858




C# - DirectX 게임 클라이언트 실행 중 키보드 입력을 감지하는 방법

각종 키보드 입력 감지 기술들이,

Low level keyboard input from Windows
; https://stackoverflow.com/questions/310576/low-level-keyboard-input-from-windows

DirectX 게임에 대해서는 통하지 않습니다. 예전에 소개한 RawInput 조차도,

RawInput을 이용한 키보드/마우스 입력 모니터링
; https://www.sysnet.pe.kr/2/0/11615

마찬가지인데요, 이것이 가능하려면 보다 하위 기술로 내려가야 하는데 일례로 커널 레벨에서 키보드 장치에 대한 driver를 직접 필터링하는 식이어야 합니다.

Keyboard Hooking In Kernel
; https://www.codeproject.com/Articles/194729/Keyboard-Hooking-In-Kernel

문제는, 저런 DDK 소스 코드를 빌드해 정상적인 인증서로 서명하지 않으면 윈도우 환경을 "testsigning" 모드로 두어야 하는데 이것 또한 은근 보안 위협에 노출될 수 있고 게다가 특정 게임 보안 프로그램에서는 아예 testsigning 환경에서는 게임을 실행하지 못하게 하는 경우도 있습니다.




이런 상황에 대한 우회 해결책으로 지난 글에서 설명한,

C# - (Wireshark의) USBPcap을 이용한 USB 패킷 모니터링
; https://www.sysnet.pe.kr/2/0/12215

USBPcap이 답이 될 수 있습니다. 실제로 그 글에서 소개한 소스 코드로 빌드한 ConsoleApp1.exe는 키보드 입력에 대해 DirectX 게임 실행 중에도 잘 동작하는 것을 확인할 수 있습니다.

"C:\Program Files\Wireshark\extcap\USBPcapCMD.exe" -d \\.\USBPcap1 --devices 1 -o - | ConsoleApp1.exe

게다가 USBPcap 자체에서 이미 정식 인증서로 서명한 드라이버 파일을 제공하므로 현실적으로 사용하는 데에도 아무런 불편함이 없습니다. 한 가지 아쉬운 점이 있다면, USBPcapCMD.exe의 동작 방식으로 인해 표준 입출력에 대한 redirection을 처리해야 한다는 것인데 개발하면서 디버깅하는 중에는 이 과정이 꽤나 귀찮다는 점입니다.

이런 불편함을 없애려면 USBPcapCMD.exe처럼 직접 USBPcap device driver에 접근해 필터링하는 코드를 작성하는데, 음... C/C++로 하려니 역시나 귀찮고 아무도 C#으로 컨버팅하지도 않은 듯하니... 어쩔 수 없이 그냥 제가 만들었습니다. ^^; 소스 코드는 기존 usbcap을 fork한,

stjeong / usbpcap
; https://github.com/stjeong/usbpcap

windows 하위 폴더에 csUSBPcapCMD C# 프로젝트로 만들어 두었고,

\usbpcap\windows\csUSBPcapCMD
; https://github.com/stjeong/usbpcap/tree/master/windows/csUSBPcapCMD

장치 선택을 쉽게 할 수 있도록 Wireshark에서 보여주는 번호와 일치하는 "device id"를 함께 출력하도록 했습니다.

D:\usbpcap\windows\csUSBPcapCMD\bin\Debug\netcoreapp3.1> csUSBPcapCMD.exe
Following filter control devices are available:
1 \\.\USBPcap1
  \??\USB#ROOT_HUB30#4&1148bc98&0&0#{f18a0e88-c30c-11d0-8815-00a0c906bed8}
    [Port 7]  (device id: 1) USB Composite Device
      USB Input Device
        HID Keyboard Device
      USB Input Device
        HID-compliant consumer control device
        HID-compliant system controller
    [Port 8]  (device id: 2) Generic USB Hub
      [Port 1]  (device id: 6) USB Input Device
        HID-compliant mouse
    [Port 9]  (device id: 3) USB Mass Storage Device
      ST1000LM 024 HN-M101MBB USB Device
    [Port 12]  (device id: 4) Intel(R) Wireless Bluetooth(R)
      Microsoft Bluetooth LE Enumerator
      Bluetooth Device (RFCOMM Protocol TDI)
      Microsoft Bluetooth Enumerator
        ...[생략]...
      Bluetooth Device (Personal Area Network)
    [Port 13]  (device id: 5) Wacom Tablet
      HID-Compliant Mouse
      HID-compliant vendor-defined device
      HID-compliant pen
      HID-compliant digitizer

따라서, 위와 같은 상황에서 "HID Keyboard Device"를 모니터링하고 싶다면 "csUSBPcapCMD.exe 0 1"과 같이 실행하면 됩니다.

참고로, 대부분의 기능을 별도로 USBPcapClient 라이브러리로 만들어 두었고,

usbpcap/windows/USBPcapLib/
; https://github.com/stjeong/usbpcap/tree/master/windows/USBPcapLib

NuGet에도 올렸으니,

USBPcapLib
; https://www.nuget.org/packages/USBPcapLib/

라이브러리 참조만 추가하고,

Install-Package USBPcapLib -Version 1.0.3

다음과 같은 식으로 코딩하기만 하면 됩니다. ^^ (물론, 사전에 USBPcap을 시스템에 설치해 두어야 하고, 프로그램은 반드시 관리자 권한으로 실행해야 합니다.)

using System;
using System.Collections.Generic;
using USBPcapLib;

namespace ConsoleApp1
{
    // Install-Package USBPcapLib -Version 1.0.3
    // https://github.com/stjeong/usbpcap/tree/master/windows/csUSBPcapCMD
    class Program
    {
        static void Main(string[] args)
        {
            List<string> filters = USBPcapClient.find_usbpcap_filters();

            if (filters.Count == 0)
            {
                Console.WriteLine("No filter control devices are available.");

                if (USBPcapClient.is_usbpcap_upper_filter_installed() == true)
                {
                    Console.WriteLine("Please reinstall USBPcapDriver.");
                }

                Console.WriteLine($@"USBPcap UpperFilter entry appears to be present.
Most likely you have not restarted your computer after installation.
It is possible to restart all USB devices to get USBPcap working without reboot.
{Environment.NewLine}WARNING:{Environment.NewLine}  Restarting all USB devices can result in data loss.
  If you are unsure please answer 'n' and reboot in order to use USBPcap.");

                return;
            }

            // how can I precisely specify a USB device to capture with tshark?
            // https://osqa-ask.wireshark.org/questions/53919/how-can-i-precisely-specify-a-usb-device-to-capture-with-tshark

            // Tracking only one USB Port in Filter using USBPcap
            // https://osqa-ask.wireshark.org/questions/63837/tracking-only-one-usb-port-in-filter-using-usbpcap
            int targetDeviceId = 0;
            int filterDeviceId = 1;

            if (args.Length >= 1)
            {
                targetDeviceId = int.Parse(args[0]);
            }

            if (args.Length >= 2)
            {
                filterDeviceId = int.Parse(args[1]);
            }

            Console.WriteLine("Following filter control devices are available:");
            string target = null;

            int i = 0;

            foreach (string filter in filters)
            {
                Console.WriteLine($"{i + 1} {filter}");

                string deviceList = USBPcapClient.enumerate_print_usbpcap_interactive(filter);
                Console.WriteLine(deviceList);

                if (targetDeviceId == i)
                {
                    target = filter;
                    break;
                }

                i++;
            }

            if (string.IsNullOrEmpty(target) == false)
            {
                using (USBPcapClient usbCapture = new USBPcapClient(target, filterDeviceId))
                {
                    usbCapture.HeaderRead += UsbCapture_HeaderRead;
                    usbCapture.DataRead += UsbCapture_DataRead;

                    usbCapture.start_capture();

                    usbCapture.wait_for_exit_signal();
                }
            }
        }

        private static void UsbCapture_HeaderRead(object sender, HeaderEventArgs e)
        {
            Console.WriteLine(e.Header.magic_number);
            Console.WriteLine(e.Header.version_major);
            Console.WriteLine(e.Header.version_minor);
            Console.WriteLine(e.Header.thiszone);
            Console.WriteLine(e.Header.sigfigs);
            Console.WriteLine(e.Header.snaplen);
            Console.WriteLine(e.Header.network);
        }

        static int _index = 1;

        private static void UsbCapture_DataRead(object sender, DataEventArgs e)
        {
            int pcapRecordDataSize = (int)e.Record.incl_len;

            //Console.WriteLine($"[{index}]");
            //Console.WriteLine(e.Record.ts_sec);
            //Console.WriteLine(e.Record.ts_usec);
            //Console.WriteLine(e.Record.incl_len);
            //Console.WriteLine(e.Record.orig_len);

            byte[] buf = e.Data;

            switch (e.Header.function)
            {
                case URB_FUNCTION.URB_FUNCTION_BULK_OR_INTERRUPT_TRANSFER:
                    if (e.Header.IrpDirection == IRPDierction.PDO_TO_FDO)
                    {
                        Console.Write($"[{_index}] {e.Header.bus}.{e.Header.device}.{e.Header.EndpointNumber}, {e.Header.transfer}, {e.Header.IrpDirection} : {buf.Length} - ");

                        if (e.Header.status != USBD_STATUS.USBD_STATUS_SUCCESS)
                        {
                            break;
                        }

                        if (e.Header.transfer != USBPCAP_TRANSFER_TYPE.INTERRUPT)
                        {
                            break;
                        }

                        if (buf.Length != 8)
                        {
                            break;
                        }

                        byte code = buf[2];
                        if (code == 0)
                        {
                            Console.WriteLine("key up");
                        }
                        else
                        {
                            // https://gist.github.com/MightyPork/6da26e382a7ad91b5496ee55fdc73db2
                            if (code >= 0x4 && code <= 0x1d)
                            {
                                char ch = (char)(code - 4 + (short)'a');
                                Console.WriteLine(ch + " pressed");
                            }
                            else
                            {
                                Console.WriteLine("Key pressed");
                            }
                        }
                    }
                    break;

                default:
                    break;
            }

            _index++;
        }
    }
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/1/2020]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2020-06-15 03시20분
본문에서 소개한 "Keyboard Hooking In Kernel"보다 더 간단한 소스 코드로,

HarsaroopDhillon2 / KL-Kernel-Project
; https://github.com/HarsaroopDhillon2/KL-Kernel-Project/blob/master/main.c
정성태
2022-04-25 11시22분
[anonymous] 감사히 잘 쓰고 있습니다
[guest]
2022-04-25 09시56분
@anonymous 반갑습니다. 이 코드의 가치를 아시는 분이군요. ^^
정성태

... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12110정성태1/11/202011930디버깅 기술: 154. Patch Guard로 인해 블루 스크린(BSOD)가 발생하는 사례 [5]파일 다운로드1
12109정성태1/10/20209818오류 유형: 588. Driver 프로젝트 빌드 오류 - Inf2Cat error -2: "Inf2Cat, signability test failed."
12108정성태1/10/20209843오류 유형: 587. Kernel Driver 시작 시 127(The specified procedure could not be found.) 오류 메시지 발생
12107정성태1/10/202010801.NET Framework: 877. C# - 프로세스의 모든 핸들을 열람 - 두 번째 이야기
12106정성태1/8/202012202VC++: 136. C++ - OSR Driver Loader와 같은 Legacy 커널 드라이버 설치 프로그램 제작 [1]
12105정성태1/8/202010874디버깅 기술: 153. C# - PEB를 조작해 로드된 DLL을 숨기는 방법
12104정성태1/7/202011553DDK: 9. 커널 메모리를 읽고 쓰는 NT Legacy driver와 C# 클라이언트 프로그램 [4]
12103정성태1/7/202014275DDK: 8. Visual Studio 2019 + WDK Legacy Driver 제작- Hello World 예제 [1]파일 다운로드2
12102정성태1/6/202011879디버깅 기술: 152. User 권한(Ring 3)의 프로그램에서 _ETHREAD 주소(및 커널 메모리를 읽을 수 있다면 _EPROCESS 주소) 구하는 방법
12101정성태1/5/202011225.NET Framework: 876. C# - PEB(Process Environment Block)를 통해 로드된 모듈 목록 열람
12100정성태1/3/20209260.NET Framework: 875. .NET 3.5 이하에서 IntPtr.Add 사용
12099정성태1/3/202011567디버깅 기술: 151. Windows 10 - Process Explorer로 확인한 Handle 정보를 windbg에서 조회 [1]
12098정성태1/2/202011145.NET Framework: 874. C# - 커널 구조체의 Offset 값을 하드 코딩하지 않고 사용하는 방법 [3]
12097정성태1/2/20209704디버깅 기술: 150. windbg - Wow64, x86, x64에서의 커널 구조체(예: TEB) 구조체 확인
12096정성태12/30/201911686디버깅 기술: 149. C# - DbgEng.dll을 이용한 간단한 디버거 제작 [1]
12095정성태12/27/201913103VC++: 135. C++ - string_view의 동작 방식
12094정성태12/26/201911281.NET Framework: 873. C# - 코드를 통해 PDB 심벌 파일 다운로드 방법
12093정성태12/26/201911291.NET Framework: 872. C# - 로딩된 Native DLL의 export 함수 목록 출력파일 다운로드1
12092정성태12/25/201910736디버깅 기술: 148. cdb.exe를 이용해 (ntdll.dll 등에 정의된) 커널 구조체 출력하는 방법
12091정성태12/25/201912218디버깅 기술: 147. pdb 파일을 다운로드하기 위한 symchk.exe 실행에 필요한 최소 파일 [1]
12090정성태12/24/201910892.NET Framework: 871. .NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점 [1]파일 다운로드1
12089정성태12/23/201911581디버깅 기술: 146. gflags와 _CrtIsMemoryBlock을 이용한 Heap 메모리 손상 여부 체크
12088정성태12/23/201910556Linux: 28. Linux - 윈도우의 "Run as different user" 기능을 shell에서 실행하는 방법
12087정성태12/21/201911026디버깅 기술: 145. windbg/sos - Dictionary의 entries 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12086정성태12/20/201913069디버깅 기술: 144. windbg - Marshal.FreeHGlobal에서 발생한 덤프 분석 사례
12085정성태12/20/201910808오류 유형: 586. iisreset - The data is invalid. (2147942413, 8007000d) 오류 발생 - 두 번째 이야기 [1]
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...