Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 125. WinDbg로 EXE의 EntryPoint에서 BP 거는 방법 [링크 복사], [링크+제목 복사]
조회: 12255
글쓴 사람
정성태 (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)
12692정성태6/30/20217509디버깅 기술: 180. Azure - Web App의 비정상 종료 시 남겨지는 로그 확인
12691정성태6/30/20218323개발 환경 구성: 573. 테스트 용도이지만 테스트에 적합하지 않은 Azure D1 공유(shared) 요금제
12690정성태6/28/20219109Java: 23. Azure - 자바(Java)로 만드는 Web App Service - Tomcat 호스팅
12689정성태6/25/20219681오류 유형: 730. Windows Forms 디자이너 - The class Form1 can be designed, but is not the first class in the file. [1]
12688정성태6/24/20219390.NET Framework: 1073. C# - JSON 역/직렬화 시 리플렉션 손실을 없애는 JsonSrcGen [2]파일 다운로드1
12687정성태6/22/20217418오류 유형: 729. Invalid data: Invalid artifact, java se app service only supports .jar artifact
12686정성태6/21/20219803Java: 22. Azure - 자바(Java)로 만드는 Web App Service - Java SE (Embedded Web Server) 호스팅
12685정성태6/21/202110011Java: 21. Azure Web App Service에 배포된 Java 프로세스의 메모리 및 힙(Heap) 덤프 뜨는 방법
12684정성태6/19/20218466오류 유형: 728. Visual Studio 2022부터 DTE.get_Properties 속성 접근 시 System.MissingMethodException 예외 발생
12683정성태6/18/20219894VS.NET IDE: 166. Visual Studio 2022 - Windows Forms 프로젝트의 x86 DLL 컨트롤이 Designer에서 오류가 발생하는 문제 [1]파일 다운로드1
12682정성태6/18/20217712VS.NET IDE: 165. Visual Studio 2022를 위한 Extension 마이그레이션
12681정성태6/18/20217028오류 유형: 727. .NET 2.0 ~ 3.5 + x64 환경에서 System.EnterpriseServices 참조 시 CS8012 경고
12680정성태6/18/20218101오류 유형: 726. python2.7.exe 실행 시 0xc000007b 오류
12679정성태6/18/20218696COM 개체 관련: 23. CoInitializeSecurity의 전역 설정을 재정의하는 CoSetProxyBlanket 함수 사용법파일 다운로드1
12678정성태6/17/20217993.NET Framework: 1072. C# - CoCreateInstance 관련 Inteop 오류 정리파일 다운로드1
12677정성태6/17/20219419VC++: 144. 역공학을 통한 lxssmanager.dll의 ILxssSession 사용법 분석파일 다운로드1
12676정성태6/16/20219478VC++: 143. ionescu007/lxss github repo에 공개된 lxssmanager.dll의 CLSID_LxssUserSession/IID_ILxssSession 사용법파일 다운로드1
12675정성태6/16/20217536Java: 20. maven package 명령어 결과물로 (war가 아닌) jar 생성 방법
12674정성태6/15/20218295VC++: 142. DEFINE_GUID 사용법
12673정성태6/15/20219450Java: 19. IntelliJ - 자바(Java)로 만드는 Web App을 Tomcat에서 실행하는 방법
12672정성태6/15/202110573오류 유형: 725. IntelliJ에서 Java webapp 실행 시 "Address localhost:1099 is already in use" 오류
12671정성태6/15/202117198오류 유형: 724. Tomcat 실행 시 Failed to initialize connector [Connector[HTTP/1.1-8080]] 오류
12670정성태6/13/20218823.NET Framework: 1071. DLL Surrogate를 이용한 Out-of-process COM 개체에서의 CoInitializeSecurity 문제파일 다운로드1
12669정성태6/11/20218786.NET Framework: 1070. 사용자 정의 GetHashCode 메서드 구현은 C# 9.0의 record 또는 리팩터링에 맡기세요.
12668정성태6/11/202110492.NET Framework: 1069. C# - DLL Surrogate를 이용한 Out-of-process COM 개체 제작파일 다운로드2
12667정성태6/10/20219142.NET Framework: 1068. COM+ 서버 응용 프로그램을 이용해 CoInitializeSecurity 제약 해결파일 다운로드1
... 31  32  33  34  35  36  [37]  38  39  40  41  42  43  44  45  ...