
* Modify S5135(Python): Fix code samples * Update rules/S5135/python/how-to-fix-it/python.adoc
59 lines
1.3 KiB
Plaintext
59 lines
1.3 KiB
Plaintext
== 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]
|
|
----
|
|
from flask import Flask, request
|
|
import yaml
|
|
|
|
app = Flask(__name__)
|
|
|
|
@app.route("/example")
|
|
def example():
|
|
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]
|
|
----
|
|
from flask import Flask, request
|
|
import yaml
|
|
|
|
app = Flask(__name__)
|
|
|
|
@app.route("/example")
|
|
def example():
|
|
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[]
|
|
|
|
|