Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 125. WinDbg로 EXE의 EntryPoint에서 BP 거는 방법 [링크 복사], [링크+제목 복사]
조회: 12259
글쓴 사람
정성태 (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)
12568정성태3/18/20217249오류 유형: 705. C# 빌드 - Couldn't process file ... due to its being in the Internet or Restricted zone or having the mark of the web on the file.
12567정성태3/17/20218566개발 환경 구성: 553. Docker Desktop for Windows를 위한 k8s 대시보드 활성화 [1]
12566정성태3/17/20218912개발 환경 구성: 552. Kubernetes - kube-apiserver와 REST API 통신하는 방법 (Docker Desktop for Windows 환경)
12565정성태3/17/20216429오류 유형: 704. curl.exe 실행 시 dll not found 오류
12564정성태3/16/20216931VS.NET IDE: 160. 새 프로젝트 창에 C++/CLI 프로젝트 템플릿이 없는 경우
12563정성태3/16/20218873개발 환경 구성: 551. C# - JIRA REST API 사용 정리 (3) jira-oauth-cli 도구를 이용한 키 관리
12562정성태3/15/20219960개발 환경 구성: 550. C# - JIRA REST API 사용 정리 (2) JIRA OAuth 토큰으로 API 사용하는 방법파일 다운로드1
12561정성태3/12/20218580VS.NET IDE: 159. Visual Studio에서 개행(\n, \r) 등의 제어 문자를 치환하는 방법 - 정규 표현식 사용
12560정성태3/11/20219929개발 환경 구성: 549. ssh-keygen으로 생성한 개인키/공개키 파일을 각각 PKCS8/PEM 형식으로 변환하는 방법
12559정성태3/11/20219312.NET Framework: 1028. 닷넷 5 환경의 Web API에 OpenAPI 적용을 위한 NSwag 또는 Swashbuckle 패키지 사용 [2]파일 다운로드1
12558정성태3/10/20218845Windows: 192. Power Automate Desktop (Preview) 소개 - Bitvise SSH Client 제어 [1]
12557정성태3/10/20217477Windows: 191. 탐색기의 보안 탭에 있는 "Object name" 경로에 LEFT-TO-RIGHT EMBEDDING 제어 문자가 포함되는 문제
12556정성태3/9/20216776오류 유형: 703. PowerShell ISE의 Debug / Toggle Breakpoint 메뉴가 비활성 상태인 경우
12555정성태3/8/20218765Windows: 190. C# - 레지스트리에 등록된 DigitalProductId로부터 라이선스 키(Product Key)를 알아내는 방법파일 다운로드2
12554정성태3/8/20218607.NET Framework: 1027. 닷넷 응용 프로그램을 위한 PDB 옵션 - full, pdbonly, portable, embedded
12553정성태3/5/20219078개발 환경 구성: 548. 기존 .NET Framework 프로젝트를 .NET Core/5+ 용으로 변환해 주는 upgrade-assistant, try-convert 도구 소개 [4]
12552정성태3/5/20218336개발 환경 구성: 547. github workflow/actions에서 Visual Studio Marketplace 패키지 등록하는 방법
12551정성태3/5/20217243오류 유형: 702. 비주얼 스튜디오 - The 'CascadePackage' package did not load correctly. (2)
12550정성태3/5/20216960오류 유형: 701. Live Share 1.0.3713.0 버전을 1.0.3884.0으로 업데이트 이후 ContactServiceModelPackage 오류 발생하는 문제
12549정성태3/4/20217399오류 유형: 700. VsixPublisher를 이용한 등록 시 다양한 오류 유형 해결책
12548정성태3/4/20218155개발 환경 구성: 546. github workflow/actions에서 nuget 패키지 등록하는 방법
12547정성태3/3/20218619오류 유형: 699. 비주얼 스튜디오 - The 'CascadePackage' package did not load correctly.
12546정성태3/3/20218285개발 환경 구성: 545. github workflow/actions에서 빌드시 snk 파일 다루는 방법 - Encrypted secrets
12545정성태3/2/202111011.NET Framework: 1026. 닷넷 5에 추가된 POH (Pinned Object Heap) [10]
12544정성태2/26/202111171.NET Framework: 1025. C# - Control의 Invalidate, Update, Refresh 차이점 [2]
12543정성태2/26/20219607VS.NET IDE: 158. C# - 디자인 타임(design-time)과 런타임(runtime)의 코드 실행 구분
... 31  32  33  34  35  36  37  38  39  40  41  [42]  43  44  45  ...