2023-03-07 17:16:47 +01:00
|
|
|
== How to fix it in PyYAML
|
|
|
|
|
|
|
|
=== Code examples
|
2022-11-04 09:20:52 +01:00
|
|
|
|
|
|
|
The following code is vulnerable to deserialization attacks because it
|
|
|
|
deserializes untrusted data without validating it first.
|
|
|
|
|
|
|
|
==== Noncompliant code example
|
|
|
|
|
2023-08-21 15:22:49 +02:00
|
|
|
[source,python,diff-id=11,diff-type=noncompliant]
|
2022-11-04 09:20:52 +01:00
|
|
|
----
|
|
|
|
def unsafe():
|
|
|
|
obj = yaml.load(request.args.get("object"), Loader=yaml.Loader)
|
|
|
|
return str(obj["status"] == "OK")
|
|
|
|
----
|
|
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
|
2023-08-21 15:22:49 +02:00
|
|
|
[source,python,diff-id=11,diff-type=compliant]
|
2022-11-04 09:20:52 +01:00
|
|
|
----
|
|
|
|
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
|
2023-08-21 15:22:49 +02:00
|
|
|
secure `load` one. It disables loading arbitrary Python object and thus
|
2022-11-04 09:20:52 +01:00
|
|
|
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.
|
|
|
|
|
2023-08-21 15:22:49 +02:00
|
|
|
[source,python]
|
2022-11-04 09:20:52 +01:00
|
|
|
----
|
|
|
|
yaml.load(untrusted, Loader=yaml.SafeLoader)
|
|
|
|
----
|
|
|
|
|
|
|
|
include::../../common/fix/integrity-check.adoc[]
|
|
|
|
|
|
|
|
|