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

(시리즈 글이 17개 있습니다.)
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: 900. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 네 번째 이야기(Monitor.Enter 후킹)
; https://www.sysnet.pe.kr/2/0/12165

.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
정성태

... 91  92  93  94  [95]  96  97  98  99  100  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11559정성태6/25/201828618개발 환경 구성: 384. 영문 설정의 Windows 10 명령행 창(cmd.exe)의 한글 지원 [6]
11558정성태6/24/201822249.NET Framework: 775. C# 7.3 - unmanaged(blittable) 제네릭 제약파일 다운로드1
11557정성태6/22/201821703.NET Framework: 774. C# - blittable 타입이란?파일 다운로드1
11556정성태6/19/201828578.NET Framework: 773. C# 7.3 - 구조체의 고정 크기를 갖는 fixed 배열 필드에 대한 직접 접근 가능 [1]파일 다운로드1
11555정성태6/18/201820271.NET Framework: 772. C# 7.3 - 사용자 정의 타입에 fixed 적용 가능(Custom fixed)파일 다운로드1
11554정성태6/17/201822294.NET Framework: 771. C# 7.3 - 자동 구현 속성에 특성 적용 가능(Attribute on backing field)
11553정성태6/15/201821884.NET Framework: 770. C# 7.3 - 개선된 메서드 선택 규칙 3가지(Improved overload candidates)파일 다운로드1
11552정성태6/15/201823870.NET Framework: 769. C# 7.3에서 개선된 문법 4개(Support == and != for tuples, Ref Reassignment, Constraints, Stackalloc initializers)파일 다운로드1
11551정성태6/14/201820452개발 환경 구성: 383. BenchmarkDotNet 사용 시 주의 사항
11550정성태6/13/201820349.NET Framework: 768. BenchmarkDotNet으로 Span<T> 성능 측정 [2]
11549정성태6/13/201821995개발 환경 구성: 382. BenchmarkDotNet에서 생성한 BuildPlots.R 파일을 실행하는 방법
11548정성태6/13/201819238오류 유형: 470. .NET Core + BenchmarkDotNet 실행 시 프레임워크를 찾지 못하는 문제
11547정성태6/13/201824329.NET Framework: 767. BenchmarkDotNet 라이브러리 소개파일 다운로드1
11546정성태6/12/201824499.NET Framework: 766. C# 7.2의 특징 - GC 및 메모리 복사 방지를 위한 struct 타입 개선 [9]파일 다운로드1
11545정성태6/11/201822759오류 유형: 469. .NET Core 프로젝트를 Visual Studio에서 실행 시 System.BadImageFormatException 발생하는 경우 [1]
11544정성태6/10/201822340.NET Framework: 765. C# 7.2 - 숫자 리터럴의 선행 밑줄과 뒤에 오지 않는 명명된 인수
11543정성태6/9/201821912.NET Framework: 764. C# 7.2 - private protected 접근자 추가파일 다운로드1
11542정성태6/9/201860304개발 환경 구성: 381. Azure Web App 확장 예제 - Remove Custom Headers
11541정성태6/9/201819499개발 환경 구성: 380. Azure Web App 확장 배포 방법 [1]
11540정성태6/9/201820279개발 환경 구성: 379. Azure Web App 확장 예제 제작 [2]
11539정성태6/8/201820062.NET Framework: 763. .NET Core 2.1 - Tiered Compilation 도입파일 다운로드1
11538정성태6/8/201819351.NET Framework: 762. .NET Core 2.1 - 확장 도구(Tools) 관리 [1]
11537정성태6/8/201823871.NET Framework: 761. C# - SmtpClient로 SMTP + SSL/TLS 서버를 이용하는 방법 [5]
11536정성태6/7/201821486.NET Framework: 760. Microsoft Build 2018 - The future of C# 동영상 내용 정리 [1]파일 다운로드1
11535정성태6/7/201823314.NET Framework: 759. C# - System.Span<T> 성능 [1]
11534정성태6/6/201829075.NET Framework: 758. C# 7.2 - Span<T> [6]
... 91  92  93  94  [95]  96  97  98  99  100  101  102  103  104  105  ...