47 lines
1.1 KiB
Plaintext
Raw Normal View History

== How to fix it in PyYAML
=== Code examples
The following code is vulnerable to deserialization attacks because it
deserializes untrusted data without validating it first.
==== Noncompliant code example
[source,python,diff-id=11,diff-type=noncompliant]
----
def unsafe():
obj = yaml.load(request.args.get("object"), Loader=yaml.Loader)
return str(obj["status"] == "OK")
----
==== Compliant solution
[source,python,diff-id=11,diff-type=compliant]
----
def safe():
obj = yaml.safe_load(request.args.get("object"))
return str(obj["status"] == "OK")
----
=== How does this work?
include::../../common/fix/introduction.adoc[]
include::../../common/fix/safer-serialization.adoc[]
The example compliant solution uses the `safe_load` method in place of the less
secure `load` one. It disables loading arbitrary Python object and thus
prevents the execution of arbitrary or dangerous functions.
Note that the same level of security can be reached with the `load` method as
soon as a safe `Loader` component is passed to it.
[source,python]
----
yaml.load(untrusted, Loader=yaml.SafeLoader)
----
include::../../common/fix/integrity-check.adoc[]