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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...
NoWriterDateCnt.TitleFile(s)
12926정성태1/17/20227159오류 유형: 787. AKS - pod 배포 시 ErrImagePull/ImagePullBackOff 오류
12925정성태1/17/20227246개발 환경 구성: 627. AKS의 준비 단계 - ACR(Azure Container Registry)에 docker 이미지 배포
12924정성태1/15/20228729.NET Framework: 1134. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) [2]파일 다운로드1
12923정성태1/15/20227643개발 환경 구성: 626. ffmpeg.exe를 사용해 비디오 파일을 MPEG1 포맷으로 변경하는 방법
12922정성태1/14/20226696개발 환경 구성: 625. AKS - Azure Kubernetes Service 생성 및 SLO/SLA 변경 방법
12921정성태1/14/20225653개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/20226430오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
12919정성태1/13/20226254Windows: 199. Host Network Service (HNS)에 의해서 점유되는 포트
12918정성태1/13/20226491Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/20225712오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/20225441오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/20225723오류 유형: 783. Visual Studio - We didn't find any interpreters
12914정성태1/11/20227647VS.NET IDE: 172. 비주얼 스튜디오 2022의 파이선 개발 환경 지원
12913정성태1/11/20228186.NET Framework: 1133. C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법 [1]
12912정성태1/11/20228810개발 환경 구성: 623. ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법 [1]
12911정성태1/11/20226144VS.NET IDE: 171. 비주얼 스튜디오 - 더 이상 만들 수 없는 "ASP.NET Core 3.1 Web Application (.NET Framework)" 프로젝트
12910정성태1/10/20226616제니퍼 .NET: 30. 제니퍼 닷넷 적용 사례 (8) - CPU high와 DB 쿼리 성능에 문제가 함께 있는 사이트
12909정성태1/10/20228021오류 유형: 782. Visual Studio 2022 설치 시 "Couldn't install Microsoft.VisualCpp.Redist.14.Latest"
12908정성태1/10/20225869.NET Framework: 1132. C# - ref/out 매개변수의 IL 코드 처리
12907정성태1/9/20226313오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20226933.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
12905정성태1/8/20226588오류 유형: 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/20228621개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227225.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20227265오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
12901정성태1/5/20227331오류 유형: 778. C# - .NET 5+에서 warning CA1416: This call site is reachable on all platforms. '...' is only supported on: 'windows' 경고 발생
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...