Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 125. WinDbg로 EXE의 EntryPoint에서 BP 거는 방법 [링크 복사], [링크+제목 복사],
조회: 12703
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  [53]  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12310정성태9/3/202010338오류 유형: 644. Windows could not start the Elasticsearch 7.9.0 (elasticsearch-service-x64) service on Local Computer.
12309정성태9/3/202010103개발 환경 구성: 507. Elasticsearch 6.6부터 기본 추가된 한글 형태소 분석기 노리(nori) 사용법
12308정성태9/2/202011345개발 환경 구성: 506. Windows - 단일 머신에서 단일 바이너리로 여러 개의 ElasticSearch 노드를 실행하는 방법
12307정성태9/2/202012136오류 유형: 643. curl - json_parse_exception / Invalid UTF-8 start byte
12306정성태9/1/202010328오류 유형: 642. SQL Server 시작 오류 - error code 10013
12305정성태9/1/202011185Windows: 172. "Administered port exclusions"이 아닌 포트 범위 항목을 삭제하는 방법
12304정성태8/31/202010140개발 환경 구성: 505. 윈도우 - (네트워크 어댑터의 우선순위로 인한) 열거되는 IP 주소 순서를 조정하는 방법
12303정성태8/30/202010295개발 환경 구성: 504. ETW - 닷넷 프레임워크 기반의 응용 프로그램을 위한 명령행 도구 etrace 소개
12302정성태8/30/202010216.NET Framework: 936. C# - ETW 관련 Win32 API 사용 예제 코드 (5) - Private Logger파일 다운로드1
12301정성태8/30/202010511오류 유형: 641. error MSB4044: The "Fody.WeavingTask" task was not given a value for the required parameter "IntermediateDir".
12300정성태8/29/20209938.NET Framework: 935. C# - ETW 관련 Win32 API 사용 예제 코드 (4) CLR ETW Consumer파일 다운로드1
12299정성태8/27/202010859.NET Framework: 934. C# - ETW 관련 Win32 API 사용 예제 코드 (3) ETW Consumer 구현파일 다운로드1
12298정성태8/27/202010604오류 유형: 640. livekd - Could not resolve symbols for ntoskrnl.exe: MmPfnDatabase
12297정성태8/25/20209811개발 환경 구성: 503. SHA256 테스트 인증서 생성 방법
12296정성태8/24/202010225.NET Framework: 933. C# - ETW 관련 Win32 API 사용 예제 코드 (2) NT Kernel Logger파일 다운로드1
12295정성태8/24/20209673오류 유형: 639. Bitvise - Address is already in use; bind() in ListeningSocket::StartListening() failed: Windows error 10013: An attempt was made to access a socket ,,,
12293정성태8/24/202010997Windows: 171. "Administered port exclusions" 설명
12292정성태8/20/202012292.NET Framework: 932. C# - ETW 관련 Win32 API 사용 예제 코드 (1)파일 다운로드2
12291정성태8/15/202011226오류 유형: 638. error 1297: Device driver does not install on any devices, use primitive driver if this is intended.
12290정성태8/11/202011882.NET Framework: 931. C# - IP 주소에 따른 국가별 위치 확인 [8]파일 다운로드1
12289정성태8/6/20209393개발 환경 구성: 502. Portainer에 윈도우 컨테이너를 등록하는 방법
12288정성태8/5/20209392오류 유형: 637. WCF - The protocol 'net.tcp' does not have an implementation of HostedTransportConfiguration type registered.
12287정성태8/5/20209853오류 유형: 636. C# - libdl.so를 DllImport로 연결 시 docker container 내에서 System.DllNotFoundException 예외 발생
12286정성태8/5/202010706개발 환경 구성: 501. .NET Core 용 container 이미지 만들 때 unzip이 필요한 경우
12285정성태8/4/202011111오류 유형: 635. 윈도우 10 업데이트 - 0xc1900209 [2]
12284정성태8/4/202010401디버깅 기술: 169. Hyper-V의 VM에 대한 메모리 덤프를 뜨는 방법
... 46  47  48  49  50  51  52  [53]  54  55  56  57  58  59  60  ...