Microsoft MVP성태의 닷넷 이야기
VC++: 114. C++ vtable의 가상 함수 호출 가로채기 [링크 복사], [링크+제목 복사]
조회: 13188
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...
NoWriterDateCnt.TitleFile(s)
12526정성태2/1/20217548개발 환경 구성: 532. Azure Devops의 파이프라인 빌드 시 snk 파일 다루는 방법 - Secure file
12525정성태2/1/20217243개발 환경 구성: 531. Azure Devops - 파이프라인 실행 시 빌드 이벤트를 생략하는 방법
12524정성태1/31/20218286개발 환경 구성: 530. 기존 github 프로젝트를 Azure Devops의 빌드 Pipeline에 연결하는 방법 [1]
12523정성태1/31/20218294개발 환경 구성: 529. 기존 github 프로젝트를 Azure Devops의 Board에 연결하는 방법
12522정성태1/31/20219789개발 환경 구성: 528. 오라클 클라우드의 리눅스 VM - 9000 MTU Jumbo Frame 테스트
12521정성태1/31/20219832개발 환경 구성: 527. 이더넷(Ethernet) 환경의 TCP 통신에서 MSS(Maximum Segment Size) 확인 [1]
12520정성태1/30/20218323개발 환경 구성: 526. 오라클 클라우드의 VM에 ping ICMP 여는 방법
12519정성태1/30/20217460개발 환경 구성: 525. 오라클 클라우드의 VM을 외부에서 접근하기 위해 포트 여는 방법
12518정성태1/30/202124879Linux: 37. Ubuntu에 Wireshark 설치 [2]
12517정성태1/30/202112449Linux: 36. 윈도우 클라이언트에서 X2Go를 이용한 원격 리눅스의 GUI 접속 - 우분투 20.04
12516정성태1/29/20219118Windows: 188. Windows - TCP default template 설정 방법
12515정성태1/28/202110313웹: 41. Microsoft Edge - localhost에 대해 http 접근 시 무조건 https로 바뀌는 문제 [3]
12514정성태1/28/202110604.NET Framework: 1021. C# - 일렉트론 닷넷(Electron.NET) 소개 [1]파일 다운로드1
12513정성태1/28/20218620오류 유형: 698. electronize - User Profile 디렉터리에 공백 문자가 있는 경우 빌드가 실패하는 문제 [1]
12512정성태1/28/20218439오류 유형: 697. The program can't start because VCRUNTIME140.dll is missing from your computer. Try reinstalling the program to fix this problem.
12511정성태1/27/20218192Windows: 187. Windows - 도스 시절의 8.3 경로를 알아내는 방법
12510정성태1/27/20218564.NET Framework: 1020. .NET Core Kestrel 호스팅 - Razor 지원 추가 [1]파일 다운로드1
12509정성태1/27/20219526개발 환경 구성: 524. Jupyter Notebook에서 C#(F#, PowerShell) 언어 사용을 위한 환경 구성 [3]
12508정성태1/27/20218144개발 환경 구성: 523. Jupyter Notebook - Slide 플레이 버튼이 없는 경우
12507정성태1/26/20218247VS.NET IDE: 157. Visual Studio - Syntax Visualizer 메뉴가 없는 경우
12506정성태1/25/202111496.NET Framework: 1019. Microsoft.Tye 기본 사용법 소개 [1]
12505정성태1/23/20219292.NET Framework: 1018. .NET Core Kestrel 호스팅 - Web API 추가 [1]파일 다운로드1
12504정성태1/23/202110405.NET Framework: 1017. .NET 5에서의 네트워크 라이브러리 개선 (2) - HTTP/2, HTTP/3 관련 [1]
12503정성태1/21/20218676오류 유형: 696. C# - HttpClient: Requesting HTTP version 2.0 with version policy RequestVersionExact while HTTP/2 is not enabled.
12502정성태1/21/20219400.NET Framework: 1016. .NET Core HttpClient의 HTTP/2 지원파일 다운로드1
12501정성태1/21/20218460.NET Framework: 1015. .NET 5부터 HTTP/1.1, 2.0 선택을 위한 HttpVersionPolicy 동작 방식파일 다운로드1
... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...