Full name: PyYAML: Py, for Python, joined to YAML, which stands for YAML Ain’t Markup Language.
Definition
PyYAML is a Python §12.23 library that reads and writes YAML (YAML Ain’t Markup Language), a text format for configuration files and structured data. Reading YAML text into Python objects is called loading; writing objects out as YAML is called dumping. PyYAML offers several loaders, which differ in what objects a document can make them build. The safe loader, used by yaml.safe_load, builds only plain data such as dictionaries, lists, strings and numbers. The unsafe loader can create objects of any class and call functions. PyYAML implements YAML version 1.1.
The idea
YAML is popular for files that people write by hand: indentation replaces brackets, and most text needs no quotation marks. The line limit: 16 on its own is a complete YAML document, which PyYAML loads as the dictionary {'limit': 16}.
Two features make reading YAML riskier than it looks. First, a document can state the type of each value with a tag, and PyYAML’s unsafe loader maps tags such as !!python/object/apply:os.system to Python functions. A loader that obeys such tags runs code chosen by whoever wrote the document, merely by reading it. Second, YAML guesses the type of unquoted text: NO becomes False, and 010 becomes 8. Parsers that follow different versions of YAML therefore read the same file as different data. The choice of loader decides what the author of a file can make the program do, and the loaded data still has to be checked.
How it works
The YAML data model. A YAML stream holds one or more documents, separated by lines of three dashes (---). Each document is a graph of nodes of three kinds.
A scalar is a single piece of text, such as
16orhello.A sequence is an ordered list of nodes, written as lines that start with
-, or in brackets, as in[a, b].A mapping is an unordered set of key–value pairs in which every key is unique, written as lines of the form
key: value, or in braces, as in{a: 1}.
Every node has a tag that names its type, such as !!int, short for tag:yaml.org,2002:int. A document may give a tag explicitly. For an unquoted scalar without a tag, the loader chooses the tag by matching the text against a list of patterns; this is called implicit typing. A quoted scalar is a string. An anchor, written &name, labels a node, and an alias, written *name, refers to that same node again, which makes a document a graph rather than a tree.
Loading in PyYAML runs in three stages.
The scanner and the parser turn the text into a series of events, such as the start of a mapping, a scalar and the end of a mapping.
The composer builds the graph of nodes, resolving implicit tags and connecting each alias to its anchored node.
The constructor turns each node into a Python object by looking up the node’s tag in a table of constructor functions. The loader class decides what that table contains.
The loaders.
BaseLoaderdoes no implicit typing: every scalar becomes a string.SafeLoader, used byyaml.safe_load, knows only the standard YAML 1.1 tags. Null becomesNone; booleans, integers, floating-point numbers §4.49 and strings becomebool,int,floatandstr;!!binarybecomesbytes; dates and timestamps becomedatetimevalues;!!setbecomesset; sequences become lists, and mappings become dictionaries. Any other tag raisesConstructorError.FullLoaderalso builds some Python types, such as tuples. It was designed not to run code, but versions before 5.4 could still be made to run code.UnsafeLoader, andLoader, its older name, accept tags of the form!!python/..., which import modules, create objects of any class and call any function.
Since PyYAML 6.0, the general function yaml.load requires the loader as an argument, and yaml.safe_load is yaml.load with SafeLoader. CSafeLoader applies the same tags faster, through libyaml, a YAML library written in C, when PyYAML was built with it.
Worked example
Six lines of configuration, loaded with yaml.safe_load in PyYAML 6.0.3:
limit: 010
enabled: no
country: NO
version: 1.10
ratio: 1e3
window: 1:30
The result is:
{'limit': 8, 'enabled': False, 'country': False,
'version': 1.1, 'ratio': '1e3', 'window': 90}
Each value follows a YAML 1.1 rule.
010has a leading zero, which marks an octal (base 8) number: .noandNOare YAML 1.1 spellings of false, so the country code of Norway becomesFalse.1.10is a floating-point number equal to 1.1, so the version text loses its last digit.1e3stays a string, because PyYAML’s pattern for floating-point numbers requires a decimal point;1.0e+3would give 1000.0.1:30is a base-60 number in YAML 1.1: .
A parser that follows YAML 1.2, the current version, with its core schema reads the same lines differently: limit is 10, because a leading zero no longer means octal; enabled and country are the strings 'no' and 'NO', because only true and false, in a few capitalizations, are booleans; version is 1.1 as before; ratio is 1000.0, because ; and window is the string '1:30'. Five of the six values differ between the two parsers. Quoting each value that must stay text, as in country: "NO" and version: "1.10", removes the guessing for both.
The tag attack. The document !!python/object/apply:os.system ["echo owned"] asks the loader to call os.system, which runs a shell command. yaml.load with UnsafeLoader runs the command while loading. yaml.safe_load raises ConstructorError, because it has no constructor for that tag, and runs nothing.
The alias attack, also called billion laughs. The line for a anchors, as &a, a list of nine strings "lol". The line for b anchors, as &b, a list of nine aliases *a, and so on, letter by letter, up to i. The document has fewer than 400 bytes. yaml.safe_load loads it in about a millisecond, because each alias becomes one more reference to an object already built. A program that then walks the result as a tree, for example to convert it to JSON §12.26 (JavaScript Object Notation), meets strings. Writing them out takes at least bytes, about 1.8 GiB, for the five characters of each quoted string alone.
Stated precisely
The contract of yaml.safe_load in PyYAML 6 has three parts.
It reads exactly one document; a stream with two documents raises
ComposerError, andyaml.safe_load_allreads several.It returns a value built only from
None,bool,int,float,str,bytes,datetime.date,datetime.datetime,list,dict,setand, inside the lists built for the ordered-mapping tags!!omapand!!pairs,tuple. Otherwise it raises an exception: normally one derived fromyaml.YAMLError, andRecursionErrorfor nesting deeper than Python’s recursion limit allows.It imports no module and calls no function or class that the document names.
The contract holds on one assumption: no code in the process has added constructors to SafeLoader. A call to yaml.add_constructor with Loader=yaml.SafeLoader changes what every later safe_load call in the same process accepts. The contract says nothing about which keys are present, what types and sizes the values have, whether a key was repeated, or how much work a consumer of the result will do.
Limits and common mistakes
Safe loading limits construction, not meaning. A safe_load result can lack required keys, carry values of the wrong type, or hold huge values. Check it against a schema, for example with JSON Schema §12.27, and against the application’s own rules before any decision uses it.
Duplicate keys pass silently, although YAML forbids them: a: 1 followed by a: 2 loads as {'a': 2}. Keys spelled differently can collide after implicit typing: null: 1 followed by ~: 2 loads as {None: 2}, because both spellings mean null. Keys that YAML treats as different can collide in Python: {1: a, 1.0: b, true: c} loads as {1: 'c'}, because Python treats 1, 1.0 and True as the same dictionary key. ruamel.yaml, another Python YAML library, rejects duplicate keys by default.
Implicit typing follows YAML 1.1, so other YAML parsers can read the same file differently, as the worked example shows. Quote every value that must stay text, or load with BaseLoader, which returns strings only, and convert each value deliberately.
Aliases can make the result, read as a tree, exponentially larger than the text. For untrusted input, bound the size of the text and refuse aliases: pass the text to yaml.parse with Loader=yaml.SafeLoader, which yields the parser’s events, and reject the text if any event is an AliasEvent.
Loaders of the same library differ in resource behavior. In a test, a text of 2000 nested brackets made the pure-Python SafeLoader raise RecursionError at Python’s default recursion limit, while CSafeLoader accepted it.
Never pass text that anyone other than the program’s authors can write to yaml.load with UnsafeLoader or Loader, or to yaml.unsafe_load. Dumping has a matching trap: yaml.dump writes !!python tags for arbitrary objects, which only the unsafe loaders read back, while yaml.safe_dump writes standard types only.
Questions answered
Which loader avoids constructing arbitrary Python objects from untrusted input?
The safe loader, SafeLoader, avoids it. Call yaml.safe_load, which is yaml.load with Loader=yaml.SafeLoader, or use CSafeLoader, the faster version built on the C library libyaml. The safe loader constructs only standard YAML data: None, booleans, integers, floating-point numbers, strings, bytes, dates and timestamps, lists, dictionaries and sets. For any other tag, such as !!python/object/apply:os.system, it raises ConstructorError instead of importing a module or calling a function; UnsafeLoader, also named Loader, would call that function. FullLoader is not the answer: it builds some Python objects, and versions before 5.4 could be made to run code.
The guarantee assumes that no code in the process has registered extra constructors on SafeLoader. Safe loading also limits only what is constructed. Before the program relies on the result, it still needs checks for required keys, types and value ranges, for duplicate keys, which PyYAML silently resolves to the last value, and for size, including the expansion of aliases.
Related entries: JSON Schema (§12.27), Test oracle (§10.5), Authorization (§1.7), Deserialization (§4.29), JSON (§12.26), Duplicate JSON key (§15.20). Further reading: [31].