PSC
PSC

Reputation: 103

Is it safe to pickle and unpickle python objects which contain user input strings?

I have an application with python objects (e.g. class Human).
Now I read the name of this human from a file and store it in the human.name attribute. This files content is not trusted.
Is it safe to pickle and and unpickle this human instance?
I have read about pickle beeing insecure, when the attacker can provide a pickle with a __reduce__ method.
So from what I have read it is secure to pickle this because I only add strings to my object. Am I right or is there still a risk?

import pickle
class Human:

def __init__(self, name):
    self.name = name

name = open("filepath").read()
h = Human(name)
p = pickle.dumps(h)
unpickledhuman = pickle.loads(p)

Upvotes: 1

Views: 390

Answers (1)

Mario Camilleri
Mario Camilleri

Reputation: 1557

Security wise, there is no danger from pickling and unpickling your own objects. The danger lies when you unpickle objects obtained from untrusted sources.

In this case, from what I can see from the code you provided, the data is being read in from a text file, pickled and then unpickled by yourself, and therefore there can be no risk involved.

Upvotes: 1

Related Questions