How else can you bypass the security fields in OOP? except friendly features

  • Replace private with public :) - Harry

2 answers 2

If we talk really about "protection hacks", i.e. about methods that do not require cooperation from the “cracking” class (i.e., they do not rely on the capabilities of the “friends”, methods that return pointers to members, etc.) that are initially included in the class, then one of the little-known ones ” "intentionally created holes in the language" is permission for explicitly instantiating a template to ignore access restrictions.

In the following example, without using any "hacks", "friends" or methods of the class itself, we bypass the protection of access to the private method

 #include <iostream> class Private { void private_func() { std::cout << "Pwned!" << std::endl; } }; using PTR = void (Private::*)(); PTR ptr; template <PTR ptr> struct Exploit { static inline struct D { D() { ::ptr = ptr; } } d; }; template struct Exploit<&Private::private_func>; int main() { (Private().*ptr)(); } 

The key point of this feature is in the resolution (given to us by section 14.7.2 / 12 of the language standard) to do

 template struct Exploit<&Private::private_func>; 

although the Private::private_func is private.

  • I think you have already written somewhere about this. - αλεχολυτ
  • @alexolut: Yes, it was. Right now ... Here: ru.stackoverflow.com/questions/656525/… Here it is more on the topic than there :) - AnT
  • if I'm not mistaken, then in VC ++ this is "fixed". - Croessmah

In general? Or in some specific?

Cheating type

 #define private public 

we consider unworthy of a real programmer? :) Is copying the class description from the header file with the addition of, for example, a friendly function — too?

There is an option to create your own class with a similar placement of members in memory and reinterpret_cast pointer to a single object into a pointer to your own - illegally, UB, but ... usually rolls completely :)

For example, through a pointer - if the same friend creates a pointer to something closed and returns it, such as

 class X { private: int y; friend int* z(X&x) { return &x.y; }; ... int * p = z(x); *p = 5; 

Or is it not suitable, although the friendly function is used indirectly?

Here is a variant with template function specialization. Suppose there is a certain class.

 class X { public: template<typename T> void f(const T& t) { /* ... */ } private: int p; }; 

We specialize this feature ...

 namespace { struct Y{}; } template<> void X::f(const Y&) { p = 5; } 

and all Sleight of hand and no fraud ...