Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [링크 복사], [링크+제목 복사],
조회: 14667
글쓴 사람
정성태 (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)
11821정성태2/20/201921484오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201924560오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201923712Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201921737VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201917707오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201921621Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201919756오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201918307오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201919305.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201916672오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201922548오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201919476.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201922327.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201923758디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
11807정성태1/29/201921497Windows: 156. 가상 디스크의 용량을 복구 파티션으로 인해 늘리지 못하는 경우 [4]
11806정성태1/29/201920650디버깅 기술: 122. windbg - 덤프 파일로부터 PID와 환경 변수 등의 정보를 구하는 방법
11805정성태1/28/201923386.NET Framework: 806. C# - int []와 object []의 차이로 이해하는 제네릭의 필요성 [4]파일 다운로드1
11804정성태1/24/201920962Windows: 155. diskpart - remove letter 이후 재부팅 시 다시 드라이브 문자가 할당되는 경우
11803정성태1/10/201919946디버깅 기술: 121. windbg - 닷넷 Finalizer 스레드가 멈춰있는 현상
11802정성태1/7/201921562.NET Framework: 805. 두 개의 윈도우를 각각 실행하는 방법(Windows Forms, WPF)파일 다운로드1
11801정성태1/1/201922593개발 환경 구성: 427. Netsh의 네트워크 모니터링 기능 [3]
11800정성태12/28/201821978오류 유형: 509. WCF 호출 오류 메시지 - System.ServiceModel.CommunicationException: Internal Server Error
11799정성태12/19/201823914.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법 [3]파일 다운로드1
11798정성태12/19/201822523개발 환경 구성: 426. vcpkg - "Building vcpkg.exe failed. Please ensure you have installed Visual Studio with the Desktop C++ workload and the Windows SDK for Desktop C++"
11797정성태12/19/201818228개발 환경 구성: 425. vcpkg - CMake Error: Problem with archive_write_header(): Can't create '' 빌드 오류
11796정성태12/19/201819090개발 환경 구성: 424. vcpkg - "File does not have expected hash" 오류를 무시하는 방법
... 76  77  78  79  80  81  82  83  84  85  [86]  87  88  89  90  ...