Security and the eval() issue

Some programmers will object to the use of the eval() function in our preceding blog_decode() function, claiming that it is a pervasive security problem. What's silly is the claim that eval() is a pervasive problem. It's a potential security problem if malicious code is written into the JSON representation of an object by some malicious actor. A local malicious actor has access to the Python source. Why waste their time on subtly tweaking JSON files? Why not just edit the Python source?

As a practical issue, we have to look at the transmission of the JSON documents through the internet; this is an actual security problem. However, even this problem does not indict eval() in general.

Some provisions can be made for a situation where an untrustworthy document has been tweaked by a Man-in-the-Middle (MITM) attack. Assume a JSON document is doctored while passing through a web interface that includes an untrustworthy server acting as a proxy. (SSL is the preferred method to prevent this problem, so we have to assume parts of the connection are also unsecured.)

If necessary, to cope with possible MITM attacks, we can replace eval() with a dictionary that maps from name to class. We can change the class_ =eval(some_dict['__class__']) expression to the following:

class_ = {
"Post": Post,
"Blog": Blog,
"datetime.datetime": datetime.datetime
}[some_dict['__class__']]

This will prevent problems in the event that a JSON document is passed through a non-SSL-encoded connection. It also leads to a maintenance requirement to tweak this mapping each time the application design changes to introduce new classes.

Let's see how to refactor the encode function in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset