Python Exploitation #2: Encapsulation

This week’s topic 6/21/15: Encapsulation

While other programming languages such as Java for example, enable the programmer to create private variables and attributes, Python does not currently have a built-in private type. Some have gone ahead and implemented a private type in C for CPython, but that isn’t frequently used. A more common attempt, which can easily be exploited is known as encapsulation. Where you attempt to conceal information within your classes from users. Encapsulation in Python, like a lot of the language’s features, is very easy to implement. You simply need to add two underscores(_) during attribute declaration. As I said in the previous Python Exploitation article, the best way to understand the exploitation, is to actually see it being done. So I’ll get right to it.

Written on Example class, note that in other languages || is equivalent to “or” in Python ;-)

We make a class called Character, which doesn’t inherit anything from a parent class. We make three normal attributes, followed by three encapsulated versions, which again, can be seen from the preceding double underscore (or in Python jargon, simply dunder). So far so good, now lets see what happens when we try to access all the attributes from an outside object.

No need to be embarrassed of your weight Dylan, or should I say Dean

As we can see, the normal attributes can be accessed from an outside object, ordinarily named character. But the encapsulated ones couldn’t be accessed. Bingo, we’ve hidden our attributes, mission complete. Wrong! Now for the fun part — the exploitation!

We check the directory for our object (character), and see that our encapsulated attributes have a longer name. Instead of __real_age, __real_name, and __real_weight, they are called _Character__real_age, _Character__real_name, and _Character__real_weight. Now we just need to call the extended attribute name to our object, and voilà, we have access to our so-called encapsulated private variables.

P.S. sorry for not keep these articles weekly haha I will try to write at least a few more of these at a greater frequency than before. Hope you enjoyed and learnt from the read.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.