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

(시리즈 글이 10개 있습니다.)
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

.NET Framework: 1062. Windows Forms - 폼 내에서 발생하는 마우스 이벤트를 자식 컨트롤 영역에 상관없이 수신하는 방법
; https://www.sysnet.pe.kr/2/0/12660

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




C# - USB 관련 ETW(Event Tracing for Windows)를 이용한 키보드 입력을 감지하는 방법

전에 USB 패킷 모니터링을,

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

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

이용해 키보드 입력을 감지하는 것을 다뤘는데요. 이를 위해 USBPcap의 device driver를 이용했는데 가만 보니 ETW를 이용해서도,

ETW(Event Tracing for Windows)를 이용한 닷넷 프로그램의 내부 이벤트 활용
; https://www.sysnet.pe.kr/2/0/12244

방법이 있을 듯합니다. ^^

Logging Keystrokes with Event Tracing for Windows (ETW)
; https://www.cyberpointllc.com/posts/cp-logging-keystrokes-with-event-tracing-for-windows-etw.html

게다가 소스코드까지 공개했으니,

CyberPoint / Ruxcon2016ETW
; https://github.com/CyberPoint/Ruxcon2016ETW

MSDN-WhiteKnight / HidLogger
; https://github.com/MSDN-WhiteKnight/HidLogger

숟가락만 얹으면 될 것... 같다고 생각했는데, 결정적으로 동작을 안 하는군요. ^^;




일단, 해당 소스 코드의 ETW 이벤트는,

session.Source.Dynamic.All += EventCallback;

잘 발생합니다. 문제는 EventCallback에서 키보드 관련 데이터를 가져오는 부분인데요,

private static void EventCallback(TraceEvent eventData)
{
    ulong hndl = 0;
    if (eventData.EventDataLength <= 0)
        return;

    if (eventData.PayloadNames.Contains("fid_USBPORT_URB_BULK_OR_INTERRUPT_TRANSFER"))
        hndl = FilterUsb2(eventData);
    else if (eventData.PayloadNames.Contains("fid_UCX_URB_BULK_OR_INTERRUPT_TRANSFER"))
        hndl = FilterUsb3(eventData);
    else
        return;

    if (hndl == 0)
        return;

    byte[] xferData = new byte[8];
    Array.Copy(eventData.EventData(), eventData.EventDataLength - 8, xferData, 0, 8);
    
    // ...[생략]...
}

/*
eventData
{
    <Event MSec="2596.9958"
        PID="19672" 
        PName=""
        TID="14640"
        EventName="URB_FUNCTION_BULK_OR_INTERRUPT_TRANSFER/Stop"
        ProviderName="Microsoft-Windows-USB-UCX"
        FormattedMessage="Complete URB_FUNCTION_BULK_OR_INTERRUPT_TRANSFER "
        fid_UcxController="0x767b6c00ab58"
        fid_UsbDevice="0x767b690184f8"
        fid_PipeHandle="0xffff898498178c40"
        fid_IRP_Ptr="0xffff8984981875a0"
        fid_URB_Ptr="0xffff8984b1a7c300"
        fid_UCX_URB_BULK_OR_INTERRUPT_TRANSFER="{ fid_URB_Hdr_Length:128, fid_URB_Hdr_Function:9, fid_URB_Hdr_Status:0, fid_URB_Hdr_UsbdDeviceHandle:&quot;130272414762232&quot;, fid_URB_Hdr_UsbdFlags:&quot;0&quot;, fid_URB_PipeHandle:&quot;18446613801313209408&quot;, fid_URB_TransferFlags:3, fid_URB_TransferBufferLength:8, fid_URB_TransferBuffer:&quot;18446613801312713072&quot;, fid_URB_TransferBufferMDL:&quot;0&quot;, fid_URB_ReservedMBZ:&quot;0&quot;, fid_URB_ReservedHcd:&quot;0&quot; }"
        fid_IRP_NtStatus="0"/>
} Microsoft.Diagnostics.Tracing.TraceEvent 
*/

아쉽게도 eventData.EventData()는 ETW 이벤트 관련 정보들이 반환될 뿐,

58 ab 00 6c 7b 76 00 00 f8 84 01 69 7b 76 00 00 
40 8c 17 98 84 89 ff ff 10 80 18 98 84 89 ff ff 
90 62 3f ac 84 89 ff ff 80 00 09 00 00 00 00 00 
f8 84 01 69 7b 76 00 00 00 00 00 00 00 00 00 00 
40 8c 17 98 84 89 ff ff 03 00 00 00 08 00 00 00 
d0 f9 0f 98 84 89 ff ff 00 00 00 00 00 00 00 00 
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
00 00 00 00 00 00 00 00 00 00 00 00

저 버퍼의 마지막 8바이트가 키보드로부터 전송한 데이터가 실려온 경우는 없었습니다. (아마도, 저 POC 프로젝트가 실행되던 당시에는 키보드 정보를 반환한 것 같습니다.)

그런데, 방법이 아주 없는 것은 아닙니다. FilterUsb3 메서드를 보면, "fid_URB_TransferBufferLength"를 키로 해서 8바이트 데이터를 구해 오는데,

private static ulong FilterUsb3(TraceEvent eventData, out byte[] urbBuffer)
{
    urbBuffer = null;

    ulong hndl = (ulong)GetItem(eventData, "fid_PipeHandle");
    if (hndl <= 0)
        return 0;

    // retrieve raw urb data
    object field = GetItem(eventData, "fid_UCX_URB_BULK_OR_INTERRUPT_TRANSFER");
    Dictionary<string, string> urb = _expose(field);

    // xfer buffer length is last n-bytes in eventData
    int xferDataSize = 0;
    if (!int.TryParse(urb["fid_URB_TransferBufferLength"], out xferDataSize))
        return 0;

    // usb keyboard xfer data is 8 bytes
    if (xferDataSize != 8)
        return 0;

    return hndl;
}

왠지 8바이트가 낯이 익습니다. ^^ 이름도 URB 데이터라는 걸로 봐서 "C# - (Wireshark의) USBPcap을 이용한 USB 패킷 모니터링" 글의 ReadFunction에서 봤던 바로 그 8바이트를 의미하는 듯합니다.

그렇다면 일단 키보드 데이터의 길이가 8이라는 것은 구했지만, 정작 원래의 버퍼를 구할 방법이 없습니다. 왜냐하면, urb["fid_URB_TransferBuffer"] 값이 제공되긴 하지만 그것은 버퍼 자체의 데이터가 아니라 버퍼의 포인터인데다, 사용자 영역이 아닌 커널 영역의 URB 버퍼 포인터(예를 들어 0xffff8984b1a7c300), 즉 커널 측 device driver가 다루던 URB 패킷 버퍼의 포인터이기 때문입니다.

불행 중 다행이라면 예전에 만들어 둔 커널 driver를 이용하는 경우,

커널 메모리를 읽고 쓰는 NT Legacy driver와 C# 클라이언트 프로그램
; https://www.sysnet.pe.kr/2/0/12104

다음과 같이 FilterUsb3 메서드를 확장해 키보드 데이터를 구할 수는 있습니다.

private static ulong FilterUsb3(TraceEvent eventData, out byte[] urbBuffer)
{
    // ...[생략]...

    if (ulong.TryParse(urb["fid_URB_TransferBuffer"], out ulong bufferAddress) == false)
    {
        return 0;
    }

    if (_memoryIO.IsInitialized == false)
    {
        return 0;
    }

    IntPtr ptr = new IntPtr((long)bufferAddress);
    urbBuffer = new byte[xferDataSize];
    _memoryIO.ReadMemory(ptr, urbBuffer);

    return hndl;
}

static KernelMemoryIO _memoryIO;

public static void StartCapture(string newSessionName = null)
{
    if (newSessionName != null)
        sessionName = newSessionName;

    using (var session = new TraceEventSession(sessionName, null))
    {
        if (TraceEventSession.IsElevated() != true)
        {
            Console.Out.WriteLine("[!] run as admin");
            return;
        }

        _memoryIO = new KernelMemoryIO();
        if (_memoryIO.IsInitialized == false)
        {
            Console.Out.WriteLine("[!] Failed to load KernelMemoryIO device driver");
        }

        SetupCtrlCHandler(() => { if (session != null) session.Stop(); });
        session.Source.Dynamic.All += EventCallback;
        session.EnableProvider(UsbUcx);
        session.EnableProvider(UsbPort);
        Console.WriteLine("starting capture ...");
        session.Source.Process();
    }
}

저렇게 구한 8바이트 데이터를 이제 EventCallback 메서드의 나머지 코드에 태우면 실행 시 다음과 같은 식의 출력을 볼 수 있습니다.

starting capture ...
20200625 11:44:49.143   00 00 07 00 00 00 00 00         d
20200625 11:44:49.287   00 00 00 00 00 00 00 00
20200625 11:44:56.759   00 00 00 00 00 00 00 00
20200625 11:44:56.863   00 00 17 00 00 00 00 00         t
20200625 11:44:57.031   00 00 17 00 00 00 00 00         t
20200625 11:45:49.015   00 00 00 00 00 00 00 00
20200625 11:45:49.143   00 00 28 00 00 00 00 00         [RET]

이제야 뭔가 좀 동작하는군요. ^^




하지만, 아직도 여전히 문제가 있습니다. 지난 글에서도,

ETW(Event Tracing for Windows)를 이용한 닷넷 프로그램의 내부 이벤트 활용
; https://www.sysnet.pe.kr/2/0/12244

ETW의 이벤트 발생에 다소 지연이 있다고 했는데, 이 때문에 키보드를 연타하게 되면 - 예를 들어 "test"라고 입력하면 "t", "t"와 같은 식으로 인식이 됩니다. 원인은, urb["fid_URB_TransferBuffer"]로 구하는 URB 버퍼가 재사용되고 있기 때문에 뒤늦게 해당 버퍼를 읽는 경우 마지막에 발생한 키보드 눌림이 들어가 있어 그런 현상이 발생하는 것 같습니다.

정리해 보면, 이런저런 이유로 인해 "키보드 눌림"이라는 이벤트는 (지연 시간과 함께) 수신할 수는 있지만 어떤 키인지에 대한 ETW를 통해서는 가져올 수 없다는 한계가 있습니다.

(위의 변형된 소스 코드는 github에 올려두었습니다.)




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







[최초 등록일: ]
[최종 수정일: 6/25/2021]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13641정성태6/11/20248659Linux: 71. Ubuntu 20.04를 22.04로 업데이트
13640정성태6/10/20248833Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager)
13639정성태6/8/20248443오류 유형: 906. C# MAUI - Android Emulator에서 "Waiting For Debugger"로 무한 대기
13638정성태6/8/20248524오류 유형: 905. C# MAUI - 추가한 layout XML 파일이 Resource.Layout 멤버로 나오지 않는 문제
13637정성태6/6/20248446Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법
13636정성태5/30/20248089닷넷: 2264. C# - 형식 인자로 인터페이스를 갖는 제네릭 타입으로의 형변환파일 다운로드1
13635정성태5/29/20248936Phone: 19. C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법
13634정성태5/24/20249416Phone: 18. C# MAUI - 안드로이드 플랫폼에서의 Activity 제어 [1]
13633정성태5/22/20248945스크립트: 64. 파이썬 - ASGI를 만족하는 최소한의 구현 코드
13632정성태5/20/20248560Phone: 17. C# MAUI - Android 내에 Web 서비스 호스팅
13631정성태5/19/20249322Phone: 16. C# MAUI - /Download 등의 공용 디렉터리에 접근하는 방법 [1]
13630정성태5/19/20248863닷넷: 2263. C# - Thread가 Task보다 더 빠르다는 어떤 예제(?)
13629정성태5/18/20249163개발 환경 구성: 710. Android - adb.exe를 이용한 파일 전송
13628정성태5/17/20248540개발 환경 구성: 709. Windows - WHPX(Windows Hypervisor Platform)를 이용한 Android Emulator 가속
13627정성태5/17/20248604오류 유형: 904. 파이썬 - UnicodeEncodeError: 'ascii' codec can't encode character '...' in position ...: ordinal not in range(128)
13626정성태5/15/20248873Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
13625정성태5/14/20248929닷넷: 2262. C# - Exception Filter 조건(when)을 갖는 catch 절의 IL 구조
13624정성태5/12/20248722Phone: 14. C# - MAUI에서 MediaElement 사용파일 다운로드1
13623정성태5/11/20248418닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석파일 다운로드1
13622정성태5/10/20249206닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제)파일 다운로드1
13621정성태5/10/20248637오류 유형: 903. IISExpress - Failed to register URL "..." for site "..." application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
13620정성태5/9/20248543VS.NET IDE: 190. Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
13619정성태5/7/20248860닷넷: 2259. C# - decimal 저장소의 비트 구조파일 다운로드1
13618정성태5/6/20248653닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조파일 다운로드1
13617정성태5/5/20249471닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조파일 다운로드1
13616정성태5/3/20248617닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...