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# - 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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  72  73  [74]  75  ...
NoWriterDateCnt.TitleFile(s)
11797정성태12/19/201810582개발 환경 구성: 425. vcpkg - CMake Error: Problem with archive_write_header(): Can't create '' 빌드 오류
11796정성태12/19/201810230개발 환경 구성: 424. vcpkg - "File does not have expected hash" 오류를 무시하는 방법
11795정성태12/19/201812666Windows: 154. PowerShell - Zone 별로 DNS 레코드 유형 정보 조회 [1]
11794정성태12/16/201810010오류 유형: 508. Get-AzureWebsite : Request to a downlevel service failed.
11793정성태12/16/201811659개발 환경 구성: 423. NuGet 패키지 제작 - Native와 Managed DLL을 분리하는 방법 [1]
11792정성태12/11/201812411Graphics: 34. .NET으로 구현하는 OpenGL (11) - Per-Pixel Lighting파일 다운로드1
11791정성태12/11/201812421VS.NET IDE: 130. C/C++ 프로젝트의 시작 프로그램으로 .NET Core EXE를 지정하는 경우 닷넷 디버깅이 안 되는 문제 [1]
11790정성태12/11/201810738오류 유형: 507. Could not save daemon configuration to C:\ProgramData\Docker\config\daemon.json: Access to the path 'C:\ProgramData\Docker\config' is denied.
11789정성태12/10/201820646Windows: 153. C# - USB 장치의 연결 및 해제 알림을 위한 WM_DEVICECHANGE 메시지 처리 [2]파일 다운로드2
11788정성태12/4/201810559오류 유형: 506. SqlClient - Value was either too large or too small for an Int32.Couldn't store <2151292191> in ... Column
11787정성태11/29/201814534Graphics: 33. .NET으로 구현하는 OpenGL (9), (10) - OBJ File Format, Loading 3D Models파일 다운로드1
11786정성태11/29/201811176오류 유형: 505. OpenGL.NET 예제 실행 시 "Managed Debugging Assistant 'CallbackOnCollectedDelegate'" 예외 발생
11785정성태11/21/201813601디버깅 기술: 120. windbg 분석 사례 - ODP.NET 사용 시 Finalizer에서 System.AccessViolationException 예외 발생으로 인한 비정상 종료
11784정성태11/18/201813298Graphics: 32. .NET으로 구현하는 OpenGL (7), (8) - Matrices and Uniform Variables, Model, View & Projection Matrices파일 다운로드1
11783정성태11/18/201811388오류 유형: 504. 윈도우 환경에서 docker가 설치된 컴퓨터 간의 ping IP 주소 풀이 오류
11782정성태11/18/201811154Windows: 152. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선순위 조정 기능 - 두 번째 이야기
11781정성태11/17/201813368개발 환경 구성: 422. SFML.NET 라이브러리 설정 방법 [1]파일 다운로드1
11780정성태11/17/201814845오류 유형: 503. vcpkg install bzip2 빌드 에러 - "Error: Building package bzip2:x86-windows failed with: BUILD_FAILED"
11779정성태11/17/201815230개발 환경 구성: 421. vcpkg 업데이트 [1]
11778정성태11/14/201813017.NET Framework: 803. UWP 앱에서 한 컴퓨터(localhost, 127.0.0.1) 내에서의 소켓 연결
11777정성태11/13/201812038오류 유형: 502. Your project does not reference "..." framework. Add a reference to "..." in the "TargetFrameworks" property of your project file and then re-run NuGet restore.
11776정성태11/13/201811290.NET Framework: 802. Windows에 로그인한 계정이 마이크로소프트의 계정인지, 로컬 계정인지 알아내는 방법
11775정성태11/13/201813834Graphics: 31. .NET으로 구현하는 OpenGL (6) - Texturing파일 다운로드1
11774정성태11/8/201811692Graphics: 30. .NET으로 구현하는 OpenGL (4), (5) - Shader파일 다운로드1
11773정성태11/7/201811456Graphics: 29. .NET으로 구현하는 OpenGL (3) - Index Buffer파일 다운로드1
11772정성태11/6/201813737Graphics: 28. .NET으로 구현하는 OpenGL (2) - VAO, VBO파일 다운로드1
... 61  62  63  64  65  66  67  68  69  70  71  72  73  [74]  75  ...