0x01h
0x01h

Reputation: 925

How to implement code execution via __reduce__ for pickling?

import pickle
import os

class Inject(object):
     def __reduce__(self):
          return (os.system, ('ls',))

serialize = pickle.dumps(Inject())
command_res = pickle.loads(serialize)
print(type(command_res))

The problem is that pickle.loads returns a tuple and second element of tuple is int, so command_res will assigned to an int, but I want to get first index [0] of pickle.loads, so command_res will be assigned to str, which is the result of ls.

How can I do that?

Upvotes: 1

Views: 2068

Answers (1)

Victor Castillo Torres
Victor Castillo Torres

Reputation: 10811

The problem is that os.system doesn't return the output of the command ls, if you execute the command with the library subprocess you get the output and can get an str instead of an int, so your code would be:

import pickle
import subprocess

class Inject(object):
     def __reduce__(self):
          return (subprocess.check_output, (['ls'],))

serialize = pickle.dumps(Inject())
command_res = pickle.loads(serialize).decode()
print(type(command_res))

Upvotes: 1

Related Questions