12

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

Mark
  • 1,333
  • 1
  • 14
  • 21
  • 3
    What do you mean by "came across"? You read something that said they were insecure? You implemented something that got hacked? Or what? – Karl Knechtel Jul 22 '11 at 19:13
  • He probably read the big red warning at the top of the documentation of the pickle module in the python documentation: https://docs.python.org/3/library/pickle.html . – Maarten Derickx Sep 03 '21 at 11:23
  • Does the BSON package have same vulnerability as Pickle? – ArekBulski Jun 16 '22 at 14:41

2 Answers2

19

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.

SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
10

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.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662