Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON vs. Pickle security

I recently came across the security problems of the Python pickle and cPickle modules. Obviously, there are no real security measures implemented in pickle unless you overwrite the find_class method as a basic modification to get a bit more security. But I often heard that JSON is more secure.

Can anyone elaborate a bit on this?`Why is JSON more secure than pickle?

Thanks a lot! Mark

like image 982
Mark Avatar asked Jul 22 '11 18:07

Mark


People also ask

Is JSON safer than pickle?

Cons-1: Pickle is Unsafe Unlike JSON, which is just a piece of string, it is possible to construct malicious pickle data which will execute arbitrary code during unpickling . Therefore, we should NEVER unpickle data that could have come from an untrusted source, or that could have been tampered with.

Is pickle better than JSON?

The json module can only serialize certain types ( int, str, dict, list) while pickle is more flexible and can serialize other objects.

Should I use pickle or JSON Python?

Just use JSONPickle on the other hand is slow, insecure, and can be only parsed in Python. The only real advantage to pickle is that it can serialize arbitrary Python objects, whereas both JSON and MessagePack have limits on the type of data they can write out.

Is cPickle faster than pickle?

Difference between Pickle and cPickle: Pickle uses python class-based implementation while cPickle is written as C functions. As a result, cPickle is many times faster than pickle.


2 Answers

json is more secure because it's fundamentally more limited. The only python types that a json document can encode are unicode, int, float, NoneType, bool, list and dict. these are marshaled/unmarshalled in a basically trivial fashion that isn't vulnerable to code injection attacks.

like image 59
SingleNegationElimination Avatar answered Oct 02 '22 19:10

SingleNegationElimination


Pickle's problem is that it will can invoke arbitrary Python code. See http://nadiana.com/python-pickle-insecure for details. The JSON parser only has to create strings, numbers, lists, dicts, and so on. It never creates user-defined classes, so it doesn't need to execute arbitrary Python.

like image 39
Ned Batchelder Avatar answered Oct 02 '22 20:10

Ned Batchelder