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)
12048정성태11/12/201912564Windows: 164. GUID 이름의 볼륨에 해당하는 파티션을 찾는 방법
12047정성태11/12/201914410Windows: 163. 안전하게 eject시킨 USB 장치를 물리적인 재연결 없이 다시 인식시키는 방법
12046정성태10/29/201910385오류 유형: 577. windbg - The call to LoadLibrary(...\sos.dll) failed, Win32 error 0n193
12045정성태10/27/20199727오류 유형: 576. mstest.exe 실행 시 "Visual Studio Enterprise is required to execute the test." 오류 - 두 번째 이야기
12044정성태10/27/20199936오류 유형: 575. mstest.exe - System.Resources.MissingSatelliteAssemblyException: The satellite assembly named "Microsoft.VisualStudio.ProductKeyDialog.resources.dll, ..."
12043정성태10/27/201910756오류 유형: 574. Windows 10 설치 시 오류 - 0xC1900101 - 0x4001E
12042정성태10/26/201911159오류 유형: 573. OneDrive 하위에 위치한 Documents, Desktop 폴더에 대한 권한 변경 시 "Unable to display current owner"
12041정성태10/23/201911165오류 유형: 572. mstest.exe - The load test results database could not be opened.
12040정성태10/23/201911427오류 유형: 571. Unhandled Exception: System.Net.Mail.SmtpException: Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied
12039정성태10/22/20199826스크립트: 16. cmd.exe의 for 문에서는 ERRORLEVEL이 설정되지 않는 문제
12038정성태10/17/20199385오류 유형: 570. SQL Server 2019 RC1 - SQL Client Connectivity SDK 설치 오류
12037정성태10/15/201915617.NET Framework: 867. C# - Encoding.Default 값을 바꿀 수 있을까요?파일 다운로드1
12036정성태10/14/201916363.NET Framework: 866. C# - 고성능이 필요한 환경에서 GC가 발생하지 않는 네이티브 힙 사용파일 다운로드1
12035정성태10/13/201912496개발 환경 구성: 461. C# 8.0의 #nulable 관련 특성을 .NET Framework 프로젝트에서 사용하는 방법 [2]파일 다운로드1
12034정성태10/12/201911840개발 환경 구성: 460. .NET Core 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 [1]
12033정성태10/11/201915536개발 환경 구성: 459. .NET Framework 프로젝트에서 C# 8.0/9.0 컴파일러를 사용하는 방법
12032정성태10/8/201912010.NET Framework: 865. .NET Core 2.2/3.0 웹 프로젝트를 IIS에서 호스팅(Inproc, out-of-proc)하는 방법 - AspNetCoreModuleV2 소개
12031정성태10/7/20199444오류 유형: 569. Azure Site Extension 업그레이드 시 "System.IO.IOException: There is not enough space on the disk" 예외 발생
12030정성태10/5/201915719.NET Framework: 864. .NET Conf 2019 Korea - "닷넷 17년의 변화 정리 및 닷넷 코어 3.0" 발표 자료 [1]파일 다운로드1
12029정성태9/27/201915860제니퍼 .NET: 29. Jennifersoft provides a trial promotion on its APM solution such as JENNIFER, PHP, and .NET in 2019 and shares the examples of their application.
12028정성태9/26/201911593.NET Framework: 863. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상을 해결하기 위한 시도파일 다운로드1
12027정성태9/26/20198847오류 유형: 568. Consider app.config remapping of assembly "..." from Version "..." [...] to Version "..." [...] to solve conflict and get rid of warning.
12026정성태9/26/201912529.NET Framework: 862. C# - Active Directory의 LDAP 경로 및 정보 조회
12025정성태9/25/201910875제니퍼 .NET: 28. APM 솔루션 제니퍼, PHP, .NET 무료 사용 프로모션 2019 및 적용 사례 (8) [1]
12024정성태9/20/201912314.NET Framework: 861. HttpClient와 HttpClientHandler의 관계 [2]
12023정성태9/18/201912748.NET Framework: 860. ServicePointManager.DefaultConnectionLimit와 HttpClient의 관계파일 다운로드1
... 61  62  63  [64]  65  66  67  68  69  70  71  72  73  74  75  ...