The security problem arises from the fact that pickle will call arbitrary functions and that it will unpickle arbitrary classes, not just the ones that you might intend it to.

It seems to me that the way to make pickle safe is to limit what it can call. Unpickle can take a list of classes and it will only unpickle objects in those classes plus the built-in types (list, tuple, etc.). I imagine that in most cases, when you are unpickling, you have some idea of what the thing is that you are unpickling. If an unlisted class or arbitrary function reference is found, it raises an UnpicklingError.

There's even an example of this in the docs, but it's left to individual developers to copy the code from the documentation: Why isn't this built in?

This is still vulnerable to a class being implemented in a way that doesn't take into account how malicious unpickling might be used on it, and then someone unknowingly pickling it. We can go one step further by adding an __unpickle__ method that, if present, is the only method that is used to load a class. We would also want to add a __pickle__ method.

--- Bruce