如何破解虚拟表?

mah*_*esh 14 c++ virtual

我想知道如何更改Test虚拟表中的地址HackedVTable.

void HackedVtable()
{
    cout << "Hacked V-Table" << endl;
}

class Base
{    
public:
    virtual Test()  { cout <<"base";    }
    virtual Test1() { cout << "Test 1"; }
    void *prt;
    Base(){}
};

class Derived : public Base
{
public: 
    Test()
    {
        cout <<"derived";
    }
};

int main()
{    
    Base b1;

    b1.Test(); // how to change this so that `HackedVtable` should be called instead of `Test`?

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

答案将不胜感激.

提前致谢.

Sam*_*ell 17

这适用于32位MSVC版本(它是一些生产代码的非常简化的版本,已经使用了一年多).请注意,您的替换方法必须显式指定this参数(指针).

// you can get the VTable location either by dereferencing the
// first pointer in the object or by analyzing the compiled binary.
unsigned long VTableLocation = 0U;
// then you have to figure out which slot the function is in. this is easy
// since they're in the same order as they are declared in the class definition.
// just make sure to update the index if 1) the function declarations are
// re-ordered and/or 2) virtual methods are added/removed from any base type.
unsigned VTableOffset = 0U;
typedef void (__thiscall Base::*FunctionType)(const Base*);
FunctionType* vtable = reinterpret_cast<FunctionType*>(VTableLocation);

bool hooked = false;
HANDLE process = ::GetCurrentProcess();
DWORD protection = PAGE_READWRITE;
DWORD oldProtection;
if ( ::VirtualProtectEx( process, &vtable[VTableOffset], sizeof(int), protection, &oldProtection ) )
{
    vtable[VTableOffset] = static_cast<FunctionType>(&ReplacementMethod);

    if ( ::VirtualProtectEx( process, &vtable[VTableOffset], sizeof(int), oldProtection, &oldProtection ) )
        hooked = true;
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ork 9

V-Table是一个实现细节.

编译器不需要使用它(它恰好是实现虚函数的最简单方法).但是说每个编译器可以(并且确实)稍微不同地实现它,因此对你的问题没有答案.

如果你问我如何破解用于构建的程序的vtable:

编译器<X>版本<Y>构建<Z>

然后有人可能知道答案.

  • 说得好.此外,即使是使用V-Table的编译器,如果程序的语义允许,有时也会生成带有静态链接的代码. (3认同)

Gan*_*pur 7

void HackedVtable()
{
    cout << "Hacked V-Table" << endl;
}

class Base
{

public:
       virtual Test()  { cout <<"base";    }
       virtual Test1() { cout << "Test 1"; }
       void *prt;
       Base(){}
};

class Derived:public Base
{
    public: 
           Test() 
           {
                   cout <<"derived";
           }
};

typedef void (*FUNPTR)();
typedef struct
{
   FUNPTR funptr;
} VTable;


int main()
{

    Base b1;
    Base *b1ptr = &b;

    VTable vtable;
    vtable.funptr = HackedVtable;

    VTable *vptr = &vtable;
    memcpy ( &b1, &vptr, sizeof(long) );

    b1ptr->Test();

    //b1.Test(); // how to change this so that HackedVtable() should be called instead of Test()

    return 0;
}
Run Code Online (Sandbox Code Playgroud)