使用c++破解私人数据

Hacking private data using c++

本文关键字:数据 破解 c++ 使用      更新时间:2023-10-16

澄清:这个问题最初来自我想到的一个挑战,与实际系统的编程无关

假设我有一个类,我知道它的体系结构,我不能改变,我不想继承它,但我确实想访问它的私有数据和函数。我该怎么做?

假设我的课看起来像这样:

class A {
public:
int v = 89;
private:
int a = 5;
virtual void function(int a, int b) {
cout << a << " " << b << endl;
}
};

不久前在这个博客上偶然发现了一个巧妙的模板技巧:http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html

不要在任何生产代码中使用它,这只是一个教育性的例子!!!

它基本上利用了在模板初始化的某些部分被忽略的"私有">

template<typename Tag>
struct result {
/* export it ... */
typedef typename Tag::type type;
static type ptr;
};
template<typename Tag>
typename result<Tag>::type result<Tag>::ptr;
template<typename Tag, typename Tag::type p>
struct rob : result<Tag> {
/* fill it ... */
struct filler {
filler() { result<Tag>::ptr = p; }
};
static filler filler_obj;
};
template<typename Tag, typename Tag::type p>
typename rob<Tag, p>::filler rob<Tag, p>::filler_obj;

用法:采用以下结构:

struct A {
private:
void f() {
std::cout << "proof!" << std::endl;
}
};

创建你的"强盗">

struct Af { typedef void(A::*type)(); };
template class rob<Af, &A::f>;

使用它:

int main()
{
A a;
(a.*result<Af>::ptr)();
return 0;
}

如果只允许修改头文件,那么风险较小的破解方法是使函数/类成为类的friend

// Add
class HackA;
class A {
public:
// Add
friend class HackA;
int v = 89;
private:
int a = 5;
virtual void function(int a, int b) {
cout << a << " " << b << endl;
}
};

现在你可以使用:

class HackA {
public:
int number(A const& a) { return a.v; }
int another_number(A const& a) { return a.a; }
void target_function(A& a, int number, int another_one)
{
a.function(number, another_one);
}
};
int main()
{
A a;
HackA hacker
cout << hacker.number(a) << " " << hacker.another_number(a) << endl;
hacker.target_function(a, 9, 3);
return 0;
}