Microsoft MVP성태의 닷넷 이야기
VC++: 36. Detours 라이브러리를 이용한 Win32 API - Sleep 호출 가로채기 [링크 복사], [링크+제목 복사],
조회: 35357
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 16개 있습니다.)
VC++: 36. Detours 라이브러리를 이용한 Win32 API - Sleep 호출 가로채기
; https://www.sysnet.pe.kr/2/0/631

.NET Framework: 187. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선
; https://www.sysnet.pe.kr/2/0/942

디버깅 기술: 40. 상황별 GetFunctionPointer 반환값 정리 - x86
; https://www.sysnet.pe.kr/2/0/1027

VC++: 56. Win32 API 후킹 - Trampoline API Hooking
; https://www.sysnet.pe.kr/2/0/1231

VC++: 57. 웹 브라우저에서 Flash만 빼고 다른 ActiveX를 차단할 수 있을까?
; https://www.sysnet.pe.kr/2/0/1232

VC++: 58. API Hooking - 64비트를 고려해야 한다면? EasyHook!
; https://www.sysnet.pe.kr/2/0/1242

개발 환경 구성: 419. MIT 라이선스로 무료 공개된 Detours API 후킹 라이브러리
; https://www.sysnet.pe.kr/2/0/11764

.NET Framework: 883. C#으로 구현하는 Win32 API 후킹(예: Sleep 호출 가로채기)
; https://www.sysnet.pe.kr/2/0/12132

.NET Framework: 890. 상황별 GetFunctionPointer 반환값 정리 - x64
; https://www.sysnet.pe.kr/2/0/12143

.NET Framework: 891. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/12144

디버깅 기술: 163. x64 환경에서 구현하는 다양한 Trampoline 기법
; https://www.sysnet.pe.kr/2/0/12148

.NET Framework: 895. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법
; https://www.sysnet.pe.kr/2/0/12150

.NET Framework: 896. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법 - 두 번째 이야기 (원본 함수 호출)
; https://www.sysnet.pe.kr/2/0/12151

.NET Framework: 897. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 세 번째 이야기(Trampoline 후킹)
; https://www.sysnet.pe.kr/2/0/12152

.NET Framework: 898. Trampoline을 이용한 후킹의 한계
; https://www.sysnet.pe.kr/2/0/12153

.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법
; https://www.sysnet.pe.kr/2/0/12409





Detours 라이브러리를 이용한 Win32 API - Sleep 호출 가로채기


엄밀히, 가로채기 자체는 이미 Detours 라이브러리에서 모두 해주기 때문에 이 글의 제목은 오히려 "Detours 소개"라고 하는 것이 더 낫겠습니다. 그럼, 한 단계씩 살펴볼까요? ^^

우선, 다운로드를 받으셔야 합니다. ^^ 다음의 경로에서.

Microsoft Research Detours Package - DetoursExpress.msi (ver 2.1)
; http://research.microsoft.com/research/downloads/Details/d36340fb-4d3c-4ddd-bf5b-1db25d03713d/Details.aspx
; https://github.com/microsoft/detours

보시는 것처럼, "Microsoft Research"의 어느 팀에서 만든 것으로 보입니다. 오호... 누구보다도 마이크로소프트가 만들었기에 더욱 그 안정성을 믿을 수 있을 것 같습니다.

아쉬운 점이라면, "Express" 버전은 현실적으로 테스트 목적으로만 사용할 수 있을 뿐 상업용으로 사용할 수 있는 라이선스가 아닙니다. 즉, 만약 이를 바탕으로 제품을 개발했다면 "Professional" 버전을 구매하셔야 합니다. (자세한 사항은 "Detours"에 방문하셔서 "Licensing" 탭에서 조회할 수 있습니다. 미리 말씀드리면... 개인이 구매하기에는 마이 비쌉니다. ^^;)

다운로드 받았으면 설치를 하는데, 저 같은 경우에는 다음의 경로에 설치했습니다. (앞으로의 진행은 기본적으로 다음의 경로를 포함합니다.)

C:\Research\Detours Express 2.1

그리고, 위의 폴더에는 다음과 같은 항목들을 포함합니다.

[그림 1: Detours 내용]
how_to_use_detours_express_library_1.PNG

자! 보이시죠? Makefile!
고맙게도, Detours 소스 및 전체 samples를 한꺼번에 빌드할 수 있는 Makefile을 제공해 주고 있습니다. 빌드를 위해 도스 명령창을 띄우고 다음과 같이 입력하시면 자동으로 Makefile이 빌드됩니다.

C:\Research\Detours Express 2.1>nmake

그럼, 폴더가 다음과 같이 생성됩니다.

[그림 2: Makefile 빌드 후]
how_to_use_detours_express_library_2.PNG

\bin\
    detoured.dll
    detoured.pdb
    ...[Samples 빌드 파일]...
    
\include\
    detours.h
    
\lib\
    detoured.exp
    detoured.lib
    detours.lib




끝났습니다. ^^ 이제 간단한 샘플을 하나 골라서 제대로 되는 지 확인을 해볼까요? "간단한" 걸로다가 "/samples/simple"을 예로 들어보겠습니다. 폴더에는 다음과 같은 파일들이 있습니다.

\samples\simple\
    Makefile
    simple.cpp
    sleep5.cpp

특이하게도, simple.cpp 하나가 곧 Win32 DLL로 빌드되는 파일이고, sleep5.cpp는 "Simple.dll"을 사용(!)하는 Console 응용 프로그램입니다.

소스를 잠깐 살펴볼까요?

simple.cpp는 다음과 같이 간단하고,

#include <stdio.h>
#include <windows.h>
#include "detours.h"

static LONG dwSlept = 0;
static VOID (WINAPI * TrueSleep)(DWORD dwMilliseconds) = Sleep;

VOID WINAPI TimedSleep(DWORD dwMilliseconds)
{
    DWORD dwBeg = GetTickCount();
    TrueSleep(dwMilliseconds);
    DWORD dwEnd = GetTickCount();

    InterlockedExchangeAdd(&dwSlept, dwEnd - dwBeg);
}

BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved)
{
    LONG error;
    (void)hinst;
    (void)reserved;

    if (dwReason == DLL_PROCESS_ATTACH) 
    {
    ...[중간 생략]...
        if (error == NO_ERROR) {
            printf("simple.dll: Detoured Sleep().\n");
        }
        else {
            printf("simple.dll: Error detouring Sleep(): %d\n", error);
        }    
    }
    else if (dwReason == DLL_PROCESS_DETACH) 
    {
    ...[중간 생략]...
        printf("simple.dll: Removed Sleep() (result=%d), slept %d ticks.\n",
               error, dwSlept);
        fflush(stdout);
    }
    return TRUE;
}

sleep5.cpp는 소스를 굳이 생략하지 않아도 될 만큼 다음과 같이 매우 간단합니다.

#include <windows.h>
#include <stdio.h>

int __cdecl main(int argc, char ** argv)
{
    if (argc == 2) {
        Sleep(atoi(argv[1]) * 1000);
    }
    else {
        printf("sleep5.exe: Starting.\n");

        Sleep(5000);

        printf("sleep5.exe: Done sleeping.\n");
    }
    return 0;
}

물론, 빌드된 결과물은 좀전에 했던 "nmake"로 인해 "bin" 폴더에 있기 때문에 실행을 해보면 다음과 같이 나옵니다.

D:\workshop\XPaperBin\Research\Detours Express 2.1\bin>sleep5.exe
sleep5.exe: Starting.
sleep5.exe: Done sleeping.

잉! 바뀐 것이 없넹. ^^; detour가 제대로 동작하지 않았습니다. 여기서, detour의 단점(?)이 하나 발견됩니다. 즉, detour는 실행시간에 IAT(Import Address Table)을 바꾸는 기능은 포함하지 않습니다. 그보다, 미리 바꿔놓아야 하는 쪽을 선택했습니다. 그래서, 역시 samples 폴더 중에 하나로 포함되어 있는 setdll 예제를 빌드하면 생성되는 "setdll.exe"를 이용해서 대상 EXE 파일의 IAT 및 그 EXE가 참조하고 있는 DLL들의 IAT 내용을 미리 바꿔 놓아야 합니다. 다음은 그러한 과정을 포함한 sleep5.exe 실행 화면입니다.

C:\workshop\Research\Detours Express 2.1\bin>setdll
Usage:
    setdll [options] binary_files
Options:
    /d:file.dll  : Add file.dll binary files
    /r           : Remove extra DLLs from binary files
    /?           : This help screen.

C:\workshop\Research\Detours Express 2.1\bin>setdll /d:simple.dll sleep5.exe
Adding simple.dll to binary files.
  sleep5.exe:
    simple.dll
    KERNEL32.dll -> KERNEL32.dll

C:\workshop\Research\Detours Express 2.1\bin>sleep5.exe
simple.dll: Starting.
simple.dll: Detoured Sleep().
sleep5.exe: Starting.
sleep5.exe: Done sleeping.
simple.dll: Removed Sleep() (result=0), slept 5008 ticks.

C:\workshop\Research\Detours Express 2.1\bin>

이것으로 설명은 끝이군요. 정리해 보면, 여러분들이 Detours를 이용해 개발을 하기로 정했다면, API 가로채기를 정의할 DLL을 하나 만들고, 모든 제품 빌드 후에는 대상 EXE에 setdll.exe를 이용하여 IAT 변경을 해줘야 합니다.




마지막으로 Detours 라이브러리 관련해서 몇가지 특이사항들을 정리해 보았습니다.

- 대상 응용 프로그램이 "Windows File Protection"에 의해서 보호 받는 것이라면 IAT가 변경된 대상 모듈들은 운영체제에 의해서 다시 복원이 되어집니다. 즉, 일반적인 상황이라면 그런 모듈들에 대해서는 Detours는 무용지물입니다.

- IAT 변경으로 인해 해당 파일이 변경되기 때문에 "코드 인증"이 깨집니다. 이것 역시 어쩔 수 없는 문제입니다.

- detours 라이브러리 자체는 static library이지만, 하는 일 없이 marker 용도로 사용되는 detoured.dll이 요구됩니다. 이것을 지우는 방법은 소스 코드를 수정하면 되는 데 이에 대해서는 다음의 글을 참고하세요.

Detours에서 Detoured.dll 제거하기
; http://www.securityproof.net/zboard/bbs/view.php?id=rv&page=1&sn1=&divpage=1&sn=off&ss=on&sc=on&select_arrange=headnum&desc=asc&no=4

- 현재 (2008년 12월 10) 2.1 버전의 makefile은 VS.NET 2008과 함께 설치되는 VC++ 빌드에서는 다음과 같은 오류가 발생합니다.

       cl /nologo /Zi /MT /Gm- /W4 /WX /O1 "/I..\..\include" "/I..\include" /Gs
 /DDETOURS_X86=1 /D_X86_ /Fe..\..\bin\symtest.exe /Fd..\..\bin\symtest.pdb symte
st.cpp  /link /release /machine:x86 "..\lib\syelog.lib" "..\..\lib\detours.lib"
"..\..\lib\detoured.lib"  kernel32.lib gdi32.lib user32.lib shell32.lib  /subsys
tem:console /incremental:no /fixed:no ..\..\bin\target.lib
symtest.cpp
symtest.cpp(270) : error C2664: 'BOOL (HANDLE,PSYM_ENUMMODULES_CALLBACK64,PVOID)
' : cannot convert parameter 2 from 'overloaded-function' to 'PSYM_ENUMMODULES_CALLBACK64'
        None of the functions with this name in scope match the target type
NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.EXE"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\nmake.exe"' : return code '0x2'
Stop.

원인은 헤더 파일이 달라져서 그렇다고 합니다. 다음의 토픽에서 이를 위한 코드 수정 방법을 알려주고 있습니다. (저는 그냥 귀찮아서 ^^; Visual Studio 2005 명령어 창에서 빌드했습니다.)

Cannot make detours.lib....
; http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/fcb5a809-5404-481f-82c0-40ffa6f58c9b/




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







[최초 등록일: ]
[최종 수정일: 6/9/2021]

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

비밀번호

댓글 작성자
 



2008-12-15 11시04분
kevin25
2021-06-09 04시09분
정성태
2023-08-28 10시26분
Spartacus DLL Hijacking - Spartacus DLL Hijacking Discovery Tool
; https://github.com/Accenture/Spartacus
정성태

... 16  17  18  19  20  21  22  23  24  25  26  27  28  [29]  30  ...
NoWriterDateCnt.TitleFile(s)
12909정성태1/10/20228150오류 유형: 782. Visual Studio 2022 설치 시 "Couldn't install Microsoft.VisualCpp.Redist.14.Latest"
12908정성태1/10/20225986.NET Framework: 1132. C# - ref/out 매개변수의 IL 코드 처리
12907정성태1/9/20226513오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20227126.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
12905정성태1/8/20226792오류 유형: 780. Could not load file or assembly 'Microsoft.VisualStudio.TextTemplating.VSHost.15.0, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
12904정성태1/8/20228782개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227377.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20227432오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
12901정성태1/5/20227459오류 유형: 778. C# - .NET 5+에서 warning CA1416: This call site is reachable on all platforms. '...' is only supported on: 'windows' 경고 발생
12900정성태1/5/20229154개발 환경 구성: 622. vcpkg로 ffmpeg를 빌드하는 경우 생성될 구성 요소 제어하는 방법
12899정성태1/3/20228646개발 환경 구성: 621. windbg에서 python 스크립트 실행하는 방법 - pykd (2)
12898정성태1/2/20229215.NET Framework: 1129. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제(encode_video.c) [1]파일 다운로드1
12897정성태1/2/20228043.NET Framework: 1128. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 [4]파일 다운로드1
12896정성태1/1/202210950.NET Framework: 1127. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성파일 다운로드1
12895정성태12/31/20219406.NET Framework: 1126. C# - snagit처럼 화면 캡처를 연속으로 수행해 동영상 제작 [1]파일 다운로드1
12894정성태12/30/20217369.NET Framework: 1125. C# - DefaultObjectPool<T>의 IDisposable 개체에 대한 풀링 문제 [3]파일 다운로드1
12893정성태12/27/20218964.NET Framework: 1124. C# - .NET Platform Extension의 ObjectPool<T> 사용법 소개파일 다운로드1
12892정성태12/26/20216966기타: 83. unsigned 형의 이전 값이 최댓값을 넘어 0을 지난 경우, 값의 차이를 계산하는 방법
12891정성태12/23/20216887스크립트: 38. 파이썬 - uwsgi의 --master 옵션
12890정성태12/23/20217015VC++: 152. Golang - (문자가 아닌) 바이트 위치를 반환하는 strings.IndexRune 함수
12889정성태12/22/20219427.NET Framework: 1123. C# - (SharpDX + DXGI) 화면 캡처한 이미지를 빠르게 JPG로 변환하는 방법파일 다운로드1
12888정성태12/21/20217546.NET Framework: 1122. C# - ImageCodecInfo 사용 시 System.Drawing.Image와 System.Drawing.Bitmap에 따른 Save 성능 차이파일 다운로드1
12887정성태12/21/20219660오류 유형: 777. OpenCVSharp4를 사용한 프로그램 실행 시 "The type initializer for 'OpenCvSharp.Internal.NativeMethods' threw an exception." 예외 발생
12886정성태12/20/20217552스크립트: 37. 파이썬 - uwsgi의 --enable-threads 옵션 [2]
12885정성태12/20/20217808오류 유형: 776. uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경
12884정성태12/20/20216857개발 환경 구성: 620. Windows 10+에서 WMI root/Microsoft/Windows/WindowsUpdate 네임스페이스 제거
... 16  17  18  19  20  21  22  23  24  25  26  27  28  [29]  30  ...