Microsoft MVP성태의 닷넷 이야기
VC++: 114. C++ vtable의 가상 함수 호출 가로채기 [링크 복사], [링크+제목 복사]
조회: 13177
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 3개 있습니다.)
VC++: 112. C++의 가상 함수 테이블 (vtable)은 언제 생성될까요?
; https://www.sysnet.pe.kr/2/0/11167

VC++: 113. C++ 클래스 상속 관계의 vtable 생성 과정
; https://www.sysnet.pe.kr/2/0/11168

VC++: 114. C++ vtable의 가상 함수 호출 가로채기
; https://www.sysnet.pe.kr/2/0/11169




C++ vtable의 가상 함수 호출 가로채기

가상 함수 테이블(virtual function table)은,

C++의 가상 함수 테이블 (vtable)은 언제 생성될까요?
; https://www.sysnet.pe.kr/2/0/11167

C++ 클래스 상속 관계의 vtable 생성 과정
; https://www.sysnet.pe.kr/2/0/11168

알아본 바와 같이 일단 메모리에 올라오면 고정이고, (변경이 없다면) 재실행하는 경우에도 동일한 메모리 주소로 로딩됩니다. (ASLR인 경우에도 ImageBase를 고려한 변위는 동일하게 유지됩니다.) 이런 성질 덕분에, 가로채기 함수를 구현하는 것이 매우 쉽습니다. 다음의 코드로 예를 들어보겠습니다.

#include "stdafx.h"

class A
{
public:
    int n1 = 1;

    void func1() { n1++; }

    virtual void vfunc1() { }
};

class BonA : A
{
public:
    int n2 = 2;

    void func2() { n2++; }

    virtual void vfunc2() { }
};

int main()
{
    BonA *table = new BonA();

    return 0;
}

table 변수에 할당된 주소로부터 vtable의 포인터를 다음과 같이 구할 수 있습니다.

BonA *table = new BonA();

void **pvftable = (void **)(*(__int64 *)table);

또한 pvftable 변수를 이용해 다음과 같이 가상 함수의 주소를 차례로 구해올 수 있습니다.

for (int i = 0; i < 2; i ++)
{
    printf("vtable[%d] == 0x%x\n", i, pvftable[i]);
}

/*
출력 결과:

vtable[0] == 0x9a1361   // A::vfunc1의 주소
vtable[1] == 0x9a1131   // BonA::vfunc2의 주소
*/

만약 vtable[0]번 항목인 A::vfunc1을 가로채기하고 싶다면 다음과 같이 새로운 함수 주소를 넣어주면 됩니다.

pvftable[0] = (int *)&intercept_vfunc1;

그런데 실제로 위와 같이 코드를 실행하면 다음과 같은 예외가 발생합니다.

Exception thrown: write access violation.
**pvftable** was 0xC77B40. occurred

왜냐하면, vtable의 데이터 저장 위치가 .rdata 섹션이고 그 영역은 IMAGE_SCN_MEM_READ 속성만 지정되어 있으므로 쓰기 실패가 발생합니다. 따라서 이 작업을 성공시키려면 메모리 접근 속성을 변경해야 합니다.

DWORD dwAttr = PAGE_EXECUTE_READWRITE;
DWORD oldProtect = 0;

BOOL result = VirtualProtect(pvftable, 4, dwAttr, &oldProtect); // PAGE_EXECUTE_READWRITE 가능하게 바꾸고,

pvftable[0] = (void *)&intercept_vfunc1; // .rdata 섹션 영역에 쓰기 작업을 한 다음,

VirtualProtect(pvftable, 4, oldProtect, &dwAttr); // 다시 원복

자, 그럼 이제 intercept_vfunc1 함수에 대해 이야기해 볼까요? 대부분의 경우, 가로채기하는 함수는 전/후처리를 한 다음 원본 메서드를 호출하는 경우가 많습니다. 따라서 원본 가상 함수를 덮어 쓰기 전에 다음과 같이 별도로 주소를 복사해 놓기 마련입니다.

g_ptrOrgVFunc1 = (void *)pvftable[0];

또한, 가로채기 함수(이 글에서는 intercept_vfunc1)가 불필요한 prolog/epilog 코드를 가지지 못하도록 다음과 같이 naked 형식의 함수로 지정합니다.

int g_i = 0;
void *g_ptrOrgVFunc1 = nullptr;

__declspec(naked) void intercept_vfunc1()
{
    g_i++;

    __asm {
        jmp [g_ptrOrgVFunc1]
    }
}

다음의 소스 코드는 이 모든 것을 합친 완전한 예제를 보여줍니다.

#include "stdafx.h"
#include <Windows.h>

class A
{
public:
    int n1 = 1;

    void func1() { n1++; }

    virtual void vfunc1() 
    { 
        printf("%d\n", 50);
    }
};

class BonA : A
{
public:
    int n2 = 2;

    void func2() { n2++; }

    virtual void vfunc2() { }
};

int g_i = 0;
void *g_ptrOrgVFunc1 = nullptr;

__declspec(naked) void intercept_vfunc1()
{
    g_i++;

    __asm {
        jmp [g_ptrOrgVFunc1]
    }
}


int main()
{
    BonA *table = new BonA();

    // x86
    int **pvftable = (int **)(*(int *)table);

    g_ptrOrgVFunc1 = (void *)pvftable[0];

    DWORD dwAttr = PAGE_EXECUTE_READWRITE;
    DWORD oldProtect = 0;

    int ptrSize = sizeof(int *);
    BOOL result = VirtualProtect(pvftable, ptrSize, dwAttr, &oldProtect);

    pvftable[0] = (int *)&intercept_vfunc1;

    VirtualProtect(pvftable, ptrSize, oldProtect, &dwAttr);

    A *aInst = (A *)table;
    aInst->vfunc1();

    return 0;
}




naked로 하면 성능 영향을 최소화하면서 필요한 최소 코드를 넣을 수 있다는 장점은 있지만 아무래도 코딩하기가 불편하다는 단점이 있습니다. 그래서 다음과 같은 형식으로 preprocess에 필요한 코드를 별도의 함수로 만들어 호출하는 것도 가능합니다.

void preprocess_vfunc1()
{
    printf("g_i == %d\n", g_i);
}

__declspec(naked) void intercept_vfunc1()
{
    g_i++;
    preprocess_vfunc1();

    __asm {
        jmp [g_ptrOrgVFunc1]
    }
}

문제는, 이것이 인자를 갖는 경우에는 naked이기 때문에 인자에 따른 스택 구성을 잘 맞춰주어야 합니다. 가령, 인자 1개를 받는 가상 함수를 가로채고 싶다면 다음과 같이 전처리를 해줘야 합니다.

class A
{
public:
    int n1 = 1;

    void func1() { n1++; }

    virtual void vfunc1() 
    { 
        printf("%d\n", 50);
    }

    virtual void vfunc2(int arg1)
    {
        printf("%d\n", n1 + arg1);
    }
};

void *g_ptrOrgVFunc2 = nullptr;

void preprocess_vfunc2(int arg1)
{
    printf("g_i == %d, arg1 == %d\n", g_i, arg1);
}

__declspec(naked) void intercept_vfunc2() // 가로채기 함수는 naked 형식이므로 인자 지정이 필요 없음.
{
    g_i++;

    __asm {
        push ecx
        mov eax, [esp + 8]
        push eax
        call preprocess_vfunc2;
        add esp, 4
        pop ecx
    }

    __asm {
        jmp [g_ptrOrgVFunc2]
        ret
    }
}




참고로 위의 코드는 x64 빌드에서는 사용할 수 없습니다. 왜냐하면 naked 옵션과 함께 inline 어셈블리가 x64에서는 지원되지 않기 때문입니다. 그래도 x64의 경우 호출 규약이 단일로 통일된 덕분에 쉽게 가로채기를 구현할 수 있습니다.

아래의 코드는 x64/x86 상관없이 vtable 호출을 가로채는 코드를 보여줍니다.

#include "stdafx.h"
#include <Windows.h>

class A
{
public:
    int n1 = 1;

    void func1() { n1++; }

    virtual void vfunc1() 
    { 
        printf("%d\n", 50);
    }

    virtual void vfunc2(int arg1)
    {
        printf("%d\n", n1 + arg1);
    }
};

class BonA : A
{
public:
    int n2 = 2;

    void func2() { n2++; }

    virtual void vfunc3() { }
};

int g_i = 0;
void *g_ptrOrgVFunc1 = nullptr;
void *g_ptrOrgVFunc2 = nullptr;

void preprocess_vfunc1()
{
    printf("g_i == %d\n", g_i);
}

void preprocess_vfunc2(int arg1)
{
    printf("g_i == %d, arg1 == %d\n", g_i, arg1);
}

#if defined(_AMD64_)
typedef void(*VFunc1)(void *thisPtr);
typedef void(*VFunc2)(void *thisPtr, int arg1);

void intercept_vfunc1(void *thisPtr)
{
    g_i++;
    preprocess_vfunc1();

    VFunc1 vFunc = (VFunc1)g_ptrOrgVFunc1;
    vFunc(thisPtr);
}

void intercept_vfunc2(void *thisPtr, int arg1)
{
    g_i++;

    preprocess_vfunc2(arg1);

    VFunc2 vFunc = (VFunc2)g_ptrOrgVFunc2;
    vFunc(thisPtr, arg1);
}
#else
__declspec(naked) void intercept_vfunc1()
{
    g_i++;
    preprocess_vfunc1();

    __asm {
        jmp [g_ptrOrgVFunc1]
    }
}

__declspec(naked) void intercept_vfunc2()
{
    g_i++;

    __asm {
        push ecx
        mov eax, [esp + 8]
        push eax
        call preprocess_vfunc2;
        add esp, 4
        pop ecx
    }

    __asm {
        jmp [g_ptrOrgVFunc2]
        ret
    }
}

#endif
int main()
{
    BonA *table = new BonA();

#if defined(_AMD64_)
    // x64
    __int64 **pvftable = (__int64 **)(*(__int64 *)table);
#else
    // x86
    int **pvftable = (int **)(*(int *)table);
#endif


    for (int i = 0; i < 2; i ++)
    {
        printf("vtable[%d] == 0x%x\n", i, pvftable[i]);
    }

    g_ptrOrgVFunc1 = (void *)pvftable[0];
    g_ptrOrgVFunc2 = (void *)pvftable[1];

    DWORD dwAttr = PAGE_EXECUTE_READWRITE;
    DWORD oldProtect = 0;

    int ptrSize = sizeof(int *);

    BOOL result = VirtualProtect(pvftable, ptrSize * 2, dwAttr, &oldProtect);

#if defined(_AMD64_)
    pvftable[0] = (__int64 *)&intercept_vfunc1;
    pvftable[1] = (__int64 *)&intercept_vfunc2;
#else
    pvftable[0] = (int *)&intercept_vfunc1;
    pvftable[1] = (int *)&intercept_vfunc2;
#endif

    VirtualProtect(pvftable, ptrSize * 2, oldProtect, &dwAttr);

    A *aInst = (A *)table;

    aInst->vfunc1();
    aInst->vfunc2(5000);

    table->vfunc3();

    return 0;
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/16/2018]

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

비밀번호

댓글 작성자
 




1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13556정성태2/17/20241829Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241973닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241721VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241792닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241744닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242060닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242160Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242486개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242318개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242064개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241921Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241839닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241853오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241849Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241881오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241927VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242056Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242153개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242219닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242290닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242457닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242253닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242085닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242284닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242178닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242065닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...