Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [링크 복사], [링크+제목 복사],
조회: 5004
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

windbg - Win32 API 호출 시점에 BP 거는 방법

아래의 Q&A를 보면,

MiniDumpWriteDump API로 덤프수집을 했는데요..
; https://www.sysnet.pe.kr/3/0/5811

procdump가 생성한 덤프 파일은 정상적으로 handle 값이 보이는 반면, 단순히 MiniDumpWriteDump를 한 경우에는 그렇지 않다고 합니다. 그런데, 사실 procdump라고 해서 특별히 독자적으로 만든 덤프 코드를 쓰지는 않을 것입니다. 즉, 동일하게 MiniDumpWriteDump API를 사용할 텐데요, 그럼 혹시 procdump가 MiniDumpWriteDump를 특별한 옵션 조합으로 사용하는 것은 아닐까요? ^^

바로 그런 경우, windbg를 이용할 수 있습니다. 단순히 다음의 옵션으로 실행할 수 있는데,

dbg_win32api_1.png

// 실습을 위해 notepad를 실행시켰고 그것의 process id가 37768인 상태.

Executable: c:\temp\procdump
Arguments: -ma 37768
Start directory: c:\temp
Target architecture: Autodetect

위의 옵션으로 "Debug" 버튼을 눌러 시작하면 해당 프로세스가 시작하자마자 BP가 걸리게 됩니다. 그런데, procdump의 경우 해당 프로세스는 32비트 프로세스라서 64비트 프로세스의 덤프를 뜨지 못합니다. 그래서 procdump는 대상 프로세스가 64비트인 경우 내부 리소스에 보관한 procdump64.exe 이미지를 실행 중에 디스크에 쓰고 그것을 자식 프로세스로 실행한 다음 해당 파일을 지우는 것으로 마무리합니다.

따라서, 우리가 원하는 MiniDumpWriteDump Win32 API는 현재의 32비트 procdump.exe에서 호출하지 않고 자식 프로세스의 procdump64.exe에서 호출될 것이므로 위와 같은 설정으로 실행하게 되면 BP가 잡히질 않습니다.

그래서 제 경우에는, procdump를 windbg 내에서 어느 정도 실행하다 procdump64.exe를 디스크에 쓰는 시점에 그 파일을 별도로 procdump64_2.exe로 복사해 두었습니다. 그런 다음, 다시 windbg 시작을 다음의 옵션으로 바꾸고,

Executable: c:\temp\procdump64_2
Arguments: -ma 37768
Start directory: c:\temp
Target architecture: Autodetect

디버그 세션을 진행했습니다. 문서에 보면,

MiniDumpWriteDump function (minidumpapiset.h)
; https://learn.microsoft.com/en-us/windows/win32/api/minidumpapiset/nf-minidumpapiset-minidumpwritedump

MiniDumpWriteDump API는 dbghelp.dll 또는 dbgcore.dll에 구현됐다고 하는데요, Windows 11의 경우에는 dbgcore.dll에 있으므로 다음과 같이 DLL 로딩 시 BP가 걸리는 명령어를 수행합니다.

sxe ld:Dbgcore.dll

// 운영체제에 따라 
// sxe ld:Dbghelp.dll

그다음 'g' 키를 눌러 dbgcore.dll 로딩 시점에 멈췄으면 이제 MiniDumpWriteDump API에 bp가 걸리도록 명령어를 수행합니다.

bp Dbgcore!MiniDumpWriteDump

다시 'g' 키를 눌러 실행하면 다음과 같이 bp가 걸리는 것을 확인할 수 있습니다.

dbg_win32api_2.png

MiniDumpWriteDump의 4번째 인자에 들어가는 값이 MINIDUMP_TYPE이니까, 위의 화면에서 r9 레지스터의 값이 0x0000000000469927 == 4,626,727이므로,

0100 0110 1001 1001 0010 0111

typedef enum _MINIDUMP_TYPE {
    MiniDumpNormal                         = 0x00000000,
    MiniDumpWithDataSegs                   = 0x00000001,
    MiniDumpWithFullMemory                 = 0x00000002,
    MiniDumpWithHandleData                 = 0x00000004,
    MiniDumpFilterMemory                   = 0x00000008,

    MiniDumpScanMemory                     = 0x00000010,
    MiniDumpWithUnloadedModules            = 0x00000020,
    MiniDumpWithIndirectlyReferencedMemory = 0x00000040,
    MiniDumpFilterModulePaths              = 0x00000080,

    MiniDumpWithProcessThreadData          = 0x00000100,
    MiniDumpWithPrivateReadWriteMemory     = 0x00000200,
    MiniDumpWithoutOptionalData            = 0x00000400,
    MiniDumpWithFullMemoryInfo             = 0x00000800,

    MiniDumpWithThreadInfo                 = 0x00001000,
    MiniDumpWithCodeSegs                   = 0x00002000,
    MiniDumpWithoutAuxiliaryState          = 0x00004000,
    MiniDumpWithFullAuxiliaryState         = 0x00008000,

    MiniDumpWithPrivateWriteCopyMemory     = 0x00010000,
    MiniDumpIgnoreInaccessibleMemory       = 0x00020000,
    MiniDumpWithTokenInformation           = 0x00040000,
    MiniDumpWithModuleHeaders              = 0x00080000,

    MiniDumpFilterTriage                   = 0x00100000,
    MiniDumpWithAvxXStateContext           = 0x00200000,
    MiniDumpWithIptTrace                   = 0x00400000,
    MiniDumpScanInaccessiblePartialPages   = 0x00800000,

    MiniDumpFilterWriteCombinedMemory      = 0x01000000,
    MiniDumpValidTypeFlags                 = 0x01ffffff,
} MINIDUMP_TYPE;

대략 값의 조합이 이렇게 나옵니다.

MiniDumpWithDataSegs
MiniDumpWithFullMemory
MiniDumpWithHandleData

MiniDumpWithUnloadedModules

MiniDumpWithProcessThreadData
MiniDumpWithFullMemoryInfo

MiniDumpWithThreadInfo
MiniDumpWithFullAuxiliaryState

MiniDumpIgnoreInaccessibleMemory
MiniDumpWithTokenInformation

MiniDumpWithIptTrace

실제로 procdump를 이용한 덤프 상태와,

0:000> .dumpdebug
----- User Mini Dump Analysis

MINIDUMP_HEADER:
Version         A793 (A05D)
NumberOfStreams 19
Flags           661826
                0002 MiniDumpWithFullMemory
                0004 MiniDumpWithHandleData
                0020 MiniDumpWithUnloadedModules
                0800 MiniDumpWithFullMemoryInfo
                1000 MiniDumpWithThreadInfo
                20000 MiniDumpIgnoreInaccessibleMemory
                40000 MiniDumpWithTokenInformation
                200000 MiniDumpWithAvxXStateContext
                400000 MiniDumpWithIptTrace
...[생략]...

위에서 알아낸 방법으로 조합한 MiniDumpWriteDump의 덤프 상태가,

0:000> .dumpdebug
----- User Mini Dump Analysis

MINIDUMP_HEADER:
Version         A793 (A05D)
NumberOfStreams 18
Flags           661826
                0002 MiniDumpWithFullMemory
                0004 MiniDumpWithHandleData
                0020 MiniDumpWithUnloadedModules
                0800 MiniDumpWithFullMemoryInfo
                1000 MiniDumpWithThreadInfo
                20000 MiniDumpIgnoreInaccessibleMemory
                40000 MiniDumpWithTokenInformation
                200000 MiniDumpWithAvxXStateContext
                400000 MiniDumpWithIptTrace
...[생략]...

거의 비슷합니다. 단지, NumberOfStreams만 procdump가 하나 더 많은데요, 그래서인지 덤프 파일 크기도 procdump 쪽이 아주 약간 더 크게 나옵니다.

prodcump: 327 MB (343,619,184 bytes)
MiniDumpWriteDump: 327 MB (343,619,082 bytes)

그래도 아마... 저렇게 맞춘 정도라면 handle 명령어가 제대로 먹히지 않을까 싶군요. ^^




참고로, 위의 내용 중 적절한 시점에 procdump64.exe를 구할 수 있다고 했는데요, 이것 역시 위의 방법대로 동일하게 적용할 수 있습니다. 즉, 하위 프로세스를 생성할 것이므로 CreateProcess에 BP를 걸면 되는데요,

CreateProcessA function (processthreadsapi.h)
; https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa

문서에도 나오듯이 해당 API의 구현 모듈이 kernel32.dll이므로 다음과 같이 DLL 로딩에 BP가 걸리도록 하고,

0:000> sxe ld:kernel32.dll

0:000> g
ModLoad: 00000000`77250000 00000000`7725a000   C:\WINDOWS\System32\wow64cpu.dll
ModLoad: 00000000`75b70000 00000000`75c60000   C:\WINDOWS\SysWOW64\KERNEL32.DLL
ntdll!NtMapViewOfSection+0x14:
00007ffa`f300f304 c3              ret

BP가 걸렸으면 CreateProcess에 bp 설정을 하면 되지만,

0:000> bp KERNEL32!CreateProcessW
Couldn't resolve error at 'KERNEL32!CreateProcessW'

없다고 나옵니다. kernel32.dll의 export 함수를 조사해 보면 CreateProcessWStub을 찾을 수 있는데요, 다시 그걸로 bp 설정을 하고 그 위치에 bp가 걸릴 때까지 실행을 (두 번 정도) 'g' 키로 하면,

0:000> bp KERNEL32!CreateProcessWStub

0:000> g
ModLoad: 00000000`74f80000 00000000`751eb000   C:\WINDOWS\SysWOW64\KERNELBASE.dll
...[생략]...
ModLoad: 00000000`765f0000 00000000`7673d000   C:\WINDOWS\SysWOW64\ole32.dll
ModLoad: 00000000`692e0000 00000000`69306000   d:\tools\sysinternals\pdh.dll
ModLoad: 00000000`751f0000 00000000`7528c000   C:\WINDOWS\SysWOW64\OLEAUT32.dll
(acc0.5928): WOW64 breakpoint - code 4000001f (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
ntdll32!LdrpDoDebuggerBreak+0x2b:
77317847 cc              int     3

0:000:x86> g
SetContext failed, 0x80004005
ModLoad: 75640000 75666000   C:\WINDOWS\SysWOW64\IMM32.DLL
ModLoad: 00000000`555e0000 00000000`557a7000   C:\Program Files (x86)\Windows Kits\10\Debuggers\x86\dbghelp.dll
ModLoad: 00000000`69200000 00000000`69229000   C:\WINDOWS\SysWOW64\dbgcore.DLL
Breakpoint 0 hit
KERNEL32!CreateProcessWStub:
75b8d930 8bff            mov     edi,edi

그 순간, procdump.exe가 있던 디렉터리를 보면 procdump64.exe 파일이 있는 것을 볼 수 있습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/5/2023]

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

비밀번호

댓글 작성자
 



2023-06-01 10시06분
Hacking with Windbg - Part 1 (Notepad)
; https://www.codeproject.com/Articles/1276860/Hacking-with-Windbg-Part-1-Notepad

-------------------------------

Windows debugger trick: Breaking when a specific debugger message is printed
; https://devblogs.microsoft.com/oldnewthing/20240403-00/?p=109607

sxe out:str
ex) sxe out:*assertion failure*
정성태

1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13358정성태5/17/20233808.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233585.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233917DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233842.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234106.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233733.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234219VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233497오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233795.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233694.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234084.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233917오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235316.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236497.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234369디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234275.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234008닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234081오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234755닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234288닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234779Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234588.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234688.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234324Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233760Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233863Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...