A really, REALLY SIMPLE example of how we can inject malicius code into a Python script. For learning and documentation purposes.
This is an unoffuscated version of our malicious code (actually dummy and completely safe).
import datetime
print(int(datetime.datetime.now().timestamp() * 100000))
>>> 161791640390972
We're going to replace import
by __import__()
which allows us to import and execute one-lined code. The result will be a little obfuscated code.
print(int(__import__('datetime').datetime.now().timestamp()*100000))
>>> 161791640390972
What if the code were obfuscated AND encoded with Base64?
cHJpbnQoaW50KF9faW1wb3J0X18oJ2RhdGV0aW1lJykuZGF0ZXRpbWUubm93KCkudGltZXN0YW1wKCkqMTAwMDAwKSk=
Completely unreadable code. That's exactly what we were looking for. So, now it's time to make it executable by a Python script. But without unmask our code.
In order to keep the mask, we will use __import__()
again, to import base64
module, which will allow us to decode our little present and make it executable by exec()
.
exec(__import__('base64').b64decode('cHJpbnQoaW50KF9faW1wb3J0X18oJ2RhdGV0aW1lJykuZGF0ZXRpbWUubm93KCkudGltZXN0YW1wKCkqMTAwMDAwKSk='))
>>> 161791640390972
So, our b64 line will be decoded and executed whenever we place the line. And done!