Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [링크 복사], [링크+제목 복사],
조회: 13423
글쓴 사람
정성태 (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*
정성태

... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11937정성태6/11/201925547개발 환경 구성: 442. .NET Core 3.0 preview 5를 이용해 Windows Forms/WPF 응용 프로그램 개발 [1]
11936정성태6/10/201918484Math: 58. C# - 최소 자승법의 1차, 2차 수렴 그래프 변화 확인 [2]파일 다운로드1
11935정성태6/9/201920076.NET Framework: 843. C# - PLplot 출력을 파일이 아닌 Window 화면으로 변경
11934정성태6/7/201921421VC++: 133. typedef struct와 타입 전방 선언으로 인한 C2371 오류파일 다운로드1
11933정성태6/7/201919723VC++: 132. enum 정의를 C++11의 enum class로 바꿀 때 유의할 사항파일 다운로드1
11932정성태6/7/201918907오류 유형: 544. C++ - fatal error C1017: invalid integer constant expression파일 다운로드1
11931정성태6/6/201919414개발 환경 구성: 441. C# - CairoSharp/GtkSharp 사용을 위한 프로젝트 구성 방법
11930정성태6/5/201919954.NET Framework: 842. .NET Reflection을 대체할 System.Reflection.Metadata 소개 [1]
11929정성태6/5/201919501.NET Framework: 841. Windows Forms/C# - 클립보드에 RTF 텍스트를 복사 및 확인하는 방법 [1]
11928정성태6/5/201918363오류 유형: 543. PowerShell 확장 설치 시 "Catalog file '[...].cat' is not found in the contents of the module" 오류 발생
11927정성태6/5/201919574스크립트: 15. PowerShell ISE의 스크립트를 복사 후 PPT/Word에 붙여 넣으면 한글이 깨지는 문제 [1]
11926정성태6/4/201919998오류 유형: 542. Visual Studio - pointer to incomplete class type is not allowed
11925정성태6/4/201919899VC++: 131. Visual C++ - uuid 확장 속성과 __uuidof 확장 연산자파일 다운로드1
11924정성태5/30/201921566Math: 57. C# - 해석학적 방법을 이용한 최소 자승법 [1]파일 다운로드1
11923정성태5/30/201921136Math: 56. C# - 그래프 그리기로 알아보는 경사 하강법의 최소/최댓값 구하기파일 다운로드1
11922정성태5/29/201918596.NET Framework: 840. ML.NET 데이터 정규화파일 다운로드1
11921정성태5/28/201924502Math: 55. C# - 다항식을 위한 최소 자승법(Least Squares Method)파일 다운로드1
11920정성태5/28/201916141.NET Framework: 839. C# - PLplot 색상 제어
11919정성태5/27/201920471Math: 54. C# - 최소 자승법의 1차 함수에 대한 매개변수를 단순 for 문으로 구하는 방법 [1]파일 다운로드1
11918정성태5/25/201921253Math: 53. C# - 행렬식을 이용한 최소 자승법(LSM: Least Square Method)파일 다운로드1
11917정성태5/24/201922232Math: 52. MathNet을 이용한 간단한 통계 정보 처리 - 분산/표준편차파일 다운로드1
11916정성태5/24/201920066Math: 51. MathNET + OxyPlot을 이용한 간단한 통계 정보 처리 - Histogram파일 다운로드1
11915정성태5/24/201923188Linux: 11. 리눅스의 환경 변수 관련 함수 정리 - putenv, setenv, unsetenv
11914정성태5/24/201922188Linux: 10. 윈도우의 GetTickCount와 리눅스의 clock_gettime파일 다운로드1
11913정성태5/23/201918855.NET Framework: 838. C# - 숫자형 타입의 bit(2진) 문자열, 16진수 문자열 구하는 방법파일 다운로드1
11912정성태5/23/201918824VS.NET IDE: 137. Visual Studio 2019 버전 16.1부터 리눅스 C/C++ 프로젝트에 추가된 WSL 지원
... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...