Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 125. WinDbg로 EXE의 EntryPoint에서 BP 거는 방법 [링크 복사], [링크+제목 복사]
조회: 12258
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

WinDbg로 EXE의 EntryPoint에서 BP 거는 방법

지난 글에서,

EXE를 LoadLibrary로 로딩해 PE 헤더에 있는 EntryPoint를 직접 호출하는 방법
; https://www.sysnet.pe.kr/2/0/11858

2가지 유형의 EntryPoint를 갖는 EXE를 만들었습니다.

  1. 콘솔 프로그램: 사용자 main 함수
  2. 콘솔 프로그램: mainCRTStartup 또는 wmainCRTStartup

우선, windbg로 첫 번째 유형의 EXE 프로그램을 "Open Executable (Ctrl + E)" 메뉴로 로드해 보면 다음과 같이 나옵니다.

Microsoft (R) Windows Debugger Version 10.0.17763.132 X86
Copyright (c) Microsoft Corporation. All rights reserved.

CommandLine: c:\temp\ConsoleApplication1\Debug\exe_entry.exe

************* Path validation summary **************
Response                         Time (ms)     Location
Deferred                                       SRV*e:\Symbols*http://msdl.microsoft.com/download/symbols
Symbol search path is: SRV*e:\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is: 
ModLoad: 00840000 00859000   exe_entry.exe
ModLoad: 77560000 776fc000   ntdll.dll
ModLoad: 74c50000 74d30000   C:\WINDOWS\SysWOW64\KERNEL32.DLL
ModLoad: 759b0000 75baa000   C:\WINDOWS\SysWOW64\KERNELBASE.dll
(4f5c.730): Break instruction exception - code 80000003 (first chance)
eax=00000000 ebx=002ef000 ecx=cf060000 edx=00000000 esi=00432ea0 edi=775737ec
eip=7760f126 esp=001df5b8 ebp=001df5e4 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
ntdll!LdrpDoDebuggerBreak+0x2b:
7760f126 cc              int     3

그러니까, 운영체제의 ntdll Loader 단계부터 디버깅이 시작되는데 EntryPoint는 이후 한참(?) 후에 나오게 됩니다. 그 시점까지 진행하는 방법은 AddressOfEntryPoint를 이용해 BP를 걸면 됩니다.

이를 위해 PE 헤더를 분석해주는 도구로 AddressOfEntryPoint의 값을 구하고, 현재 EXE 모듈이 로드된 주소를 찾아서 더하면 됩니다. 모듈의 로딩 주소는 windbg의 lm 명령어로 구할 수 있으므로,

0:000> lm
start    end        module name
00840000 00859000   exe_entry   (deferred)             
74c50000 74d30000   KERNEL32   (deferred)             
759b0000 75baa000   KERNELBASE   (deferred)             
77560000 776fc000   ntdll      (pdb symbols)          e:\symbols\wntdll.pdb\06265607D3AAB293F80811D978F5F5B31\wntdll.pdb

AddressOfEntryPoint의 값이 110f라고 구해졌다면 다음과 같이 EntryPoint 주소를 구할 수 있습니다.

0:000> ? 00840000 + 1100f
Evaluate expression: 8720399 = 0085100f

따라서 이 주소에 BP를 걸고,

0:000> bp  0085100f
*** WARNING: Unable to verify checksum for exe_entry.exe

0:000> bl
     0 e Disable Clear  0085100f     0001 (0001)  0:**** exe_entry!ILT+10(_main)

g 키를 눌러 실행을 계속하면 우리가 원하던 EntryPoint에서 실행이 멈추는 것을 확인할 수 있습니다.

0:000> g
Breakpoint 0 hit
eax=001dfb60 ebx=002ef000 ecx=0085100f edx=0085100f esi=0085100f edi=0085100f
eip=0085100f esp=001dfb08 ebp=001dfb14 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
exe_entry!ILT+10(_main):
0085100f e93c000000      jmp     exe_entry!main (00851050)

(Windows 10의 경우) 이 시점에서 콜 스택은 다음과 같습니다.

exe_entry!ILT+10(_main)
ntdll!__RtlUserThreadStart+0x2f
ntdll!_RtlUserThreadStart+0x1b

결국 EntryPoint의 호출은 ntdll!__RtlUserThreadStart에서,

ntdll!__RtlUserThreadStart:
775c65fe 6a30            push    30h
775c6600 6840926677      push    offset ntdll!QueryRegistryValue+0x10da (77669240)
775c6605 e84add0100      call    ntdll!_SEH_prolog4 (775e4354)
775c660a 8bf9            mov     edi,ecx
775c660c 8365fc00        and     dword ptr [ebp-4],0
775c6610 8b351c096877    mov     esi,dword ptr [ntdll!Kernel32ThreadInitThunkFunction (7768091c)]
775c6616 52              push    edx
775c6617 85f6            test    esi,esi
775c6619 0f844ac90300    je      ntdll!__RtlUserThreadStart+0x3c96b (77602f69)
775c661f 8bce            mov     ecx,esi
775c6621 ff15e0416877    call    dword ptr [ntdll!__guard_check_icall_fptr (776841e0)]
775c6627 8bd7            mov     edx,edi
775c6629 33c9            xor     ecx,ecx
775c662b ffd6            call    esi

위의 call esi로 인해 발생하며 이때의 esi 값이 바로 0085100f입니다.




위의 경우에는 사용자가 작성한 main 함수를 EntryPoint로 지정한 EXE였기 때문에 마지막 call stack에 exe_entry!main이 나왔습니다. CRT가 연결된 EXE라면 EntryPoint의 주소는 mainCRTStartup 또는 wmainCRTStartup이 됩니다.

확인 방법 역시 위에서 설명한 것과 동일하지만 이번에는 다른 방법으로 접근해 보겠습니다. ^^

How to get to entry point with windbg
; https://stackoverflow.com/questions/13387691/how-to-get-to-entry-point-with-windbg

그렇습니다. windbg가 제공하는 가상 레지스터인 $exentry 값을 사용하면 되는 것입니다. 따라서 lm 명령이나 AddressOfEntryPoint 값을 알아낼 필요도 없이 곧바로 BP를 걸 수 있습니다.

0:000> bp $exentry
*** WARNING: Unable to verify checksum for exe_dll_entry.exe

0:000> bl
     0 e Disable Clear  002313c0     0001 (0001)  0:**** exe_dll_entry!ILT+955(_mainCRTStartup)

0:000> g
Breakpoint 0 hit
eax=006ffa8c ebx=00434000 ecx=002313c0 edx=002313c0 esi=002313c0 edi=002313c0
eip=002313c0 esp=006ffa34 ebp=006ffa40 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
exe_dll_entry!ILT+955(_mainCRTStartup):
002313c0 e92b1b0000      jmp     exe_dll_entry!mainCRTStartup (00232ef0)

보는 바와 같이 진입 지점의 함수가 "exe_dll_entry!mainCRTStartup"라고 나옵니다.




지난 글에서, EXE 모듈을 윈도우 운영체제로 하여금 DLL로써 다루도록 Characteristics에 IMAGE_FILE_DLL 속성을 부여할 수 있다고 했는데요. 재미있게도, windbg의 경우 IMAGE_FILE_DLL 속성이 부여된 EXE를 로드하는 경우 다음과 같은 오류를 발생시키며 디버깅 진입에 실패합니다.

Could not create process 'c:\temp\ConsoleApplication1\Debug\exe_dll_entry.exe', Win32 error 0n193

%1 is not a valid Win32 application.

따라서 windbg로 로드하려면 다시 IMAGE_FILE_DLL을 제거해야만 합니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/4/2019]

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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...
NoWriterDateCnt.TitleFile(s)
12517정성태1/30/202112343Linux: 36. 윈도우 클라이언트에서 X2Go를 이용한 원격 리눅스의 GUI 접속 - 우분투 20.04
12516정성태1/29/20219015Windows: 188. Windows - TCP default template 설정 방법
12515정성태1/28/202110152웹: 41. Microsoft Edge - localhost에 대해 http 접근 시 무조건 https로 바뀌는 문제 [3]
12514정성태1/28/202110500.NET Framework: 1021. C# - 일렉트론 닷넷(Electron.NET) 소개 [1]파일 다운로드1
12513정성태1/28/20218555오류 유형: 698. electronize - User Profile 디렉터리에 공백 문자가 있는 경우 빌드가 실패하는 문제 [1]
12512정성태1/28/20218357오류 유형: 697. The program can't start because VCRUNTIME140.dll is missing from your computer. Try reinstalling the program to fix this problem.
12511정성태1/27/20218097Windows: 187. Windows - 도스 시절의 8.3 경로를 알아내는 방법
12510정성태1/27/20218468.NET Framework: 1020. .NET Core Kestrel 호스팅 - Razor 지원 추가 [1]파일 다운로드1
12509정성태1/27/20219457개발 환경 구성: 524. Jupyter Notebook에서 C#(F#, PowerShell) 언어 사용을 위한 환경 구성 [3]
12508정성태1/27/20218030개발 환경 구성: 523. Jupyter Notebook - Slide 플레이 버튼이 없는 경우
12507정성태1/26/20218153VS.NET IDE: 157. Visual Studio - Syntax Visualizer 메뉴가 없는 경우
12506정성태1/25/202111393.NET Framework: 1019. Microsoft.Tye 기본 사용법 소개 [1]
12505정성태1/23/20219195.NET Framework: 1018. .NET Core Kestrel 호스팅 - Web API 추가 [1]파일 다운로드1
12504정성태1/23/202110316.NET Framework: 1017. .NET 5에서의 네트워크 라이브러리 개선 (2) - HTTP/2, HTTP/3 관련 [1]
12503정성태1/21/20218574오류 유형: 696. C# - HttpClient: Requesting HTTP version 2.0 with version policy RequestVersionExact while HTTP/2 is not enabled.
12502정성태1/21/20219294.NET Framework: 1016. .NET Core HttpClient의 HTTP/2 지원파일 다운로드1
12501정성태1/21/20218375.NET Framework: 1015. .NET 5부터 HTTP/1.1, 2.0 선택을 위한 HttpVersionPolicy 동작 방식파일 다운로드1
12500정성태1/21/20218975.NET Framework: 1014. ASP.NET Core(Kestrel)의 HTTP/2 지원 여부파일 다운로드1
12499정성태1/20/202110177.NET Framework: 1013. .NET Core Kestrel 호스팅 - 포트 변경, non-localhost 접속 지원 및 https 등의 설정 변경 [1]파일 다운로드1
12498정성태1/20/20219122.NET Framework: 1012. .NET Core Kestrel 호스팅 - 비주얼 스튜디오의 Kestrel/IIS Express 프로파일 설정
12497정성태1/20/202110022.NET Framework: 1011. C# - OWIN Web API 예제 프로젝트 [1]파일 다운로드2
12496정성태1/19/20218899.NET Framework: 1010. .NET Core 콘솔 프로젝트에서 Kestrel 호스팅 방법 [1]
12495정성태1/19/202111004웹: 40. IIS의 HTTP/2 지원 여부 - h2, h2c [1]
12494정성태1/19/202110156개발 환경 구성: 522. WSL2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 [2]
12493정성태1/18/20218582.NET Framework: 1009. .NET 5에서의 네트워크 라이브러리 개선 (1) - HTTP 관련 [1]파일 다운로드1
12492정성태1/17/20217972오류 유형: 695. ASP.NET 0x80131620 Failed to bind to address
... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...