Skip to content

Instantly share code, notes, and snippets.

@JuanjoSalvador
Last active April 8, 2021 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JuanjoSalvador/6261b4ef415901282bb6d340814a0273 to your computer and use it in GitHub Desktop.
Save JuanjoSalvador/6261b4ef415901282bb6d340814a0273 to your computer and use it in GitHub Desktop.
Python code injection: a really, REALLY SIMPLE example of how we can inject malicius code into a Python script.

HOW-TO: Python code injection

A really, REALLY SIMPLE example of how we can inject malicius code into a Python script. For learning and documentation purposes.

Base script.

This is an unoffuscated version of our malicious code (actually dummy and completely safe).

import datetime 
print(int(datetime.datetime.now().timestamp() * 100000))
>>> 161791640390972

Minifyed version.

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

MOAR obfuscation!!!!11

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment