Security and safe loading

In principle, YAML can build objects of any type. This allows an attack on an application that transmits YAML files over the internet without proper SSL controls in place.

The YAML module offers a safe_load() method that refuses to execute arbitrary Python code as part of building an object. This severely limits what can be loaded. For insecure data exchanges, we can use yaml.safe_load() to create Python dict and list objects that contain only built-in types. We can then build our application classes from the dict and list instances. This is vaguely similar to the way we use JSON or CSV to exchange dict that must be used to create a proper object.

A better approach is to use the yaml.YAMLObject mixin class for our own objects. We use this to set some class-level attributes that provide hints to yaml and ensure the safe construction of objects.

Here's how we define a superclass for safe transmission:

class Card2(yaml.YAMLObject): 
    yaml_tag = '!Card2' 
    yaml_loader = yaml.SafeLoader 

The two attributes will alert yaml that these objects can be safely loaded without executing arbitrary and unexpected Python code. Each subclass of Card2 only has to set the unique YAML tag that will be used:

class AceCard2(Card2): 
    yaml_tag = '!AceCard2' 

We've added an attribute that alerts yaml that these objects use only this class definition. The objects can be safely loaded; they don't execute arbitrary untrustworthy code.

With these modifications to the class definitions, we can now use yaml.safe_load() on the YAML stream without worrying about the document having malicious code inserted over an unsecured internet connection. The explicit use of the yaml.YAMLObject mixin class for our own objects coupled with setting the yaml_tag attribute has several advantages. It leads to slightly more compact files. It also leads to a better-looking YAML files—the long, generic !!python/object:Chapter_10.ch10_ex2.AceCard tags are replaced with shorter !AceCard2 tags.

Let's see how to dump and load using pickle.

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

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