64 lines
1.7 KiB
Plaintext
64 lines
1.7 KiB
Plaintext
== How to fix it in Python Standard Library
|
|
|
|
=== Code examples
|
|
|
|
include::../../common/fix/code-rationale.adoc[]
|
|
|
|
Especially, in this example, if the *host* request parameter contains system
|
|
shell control characters, the expected `ping` command behavior will be changed.
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,python,diff-id=11,diff-type=noncompliant]
|
|
----
|
|
from flask import Flask, request
|
|
import os
|
|
|
|
app = Flask(__name__)
|
|
|
|
@app.route('/example')
|
|
def example():
|
|
host = request.args.get("host", "www.google.com")
|
|
|
|
status = os.system("ping -c 1 %s" % host) # Noncompliant
|
|
return str(status == 0)
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,python,diff-id=11,diff-type=compliant]
|
|
----
|
|
from flask import Flask, request
|
|
import os
|
|
|
|
app = Flask(__name__)
|
|
|
|
@app.route('/example')
|
|
def example():
|
|
host = request.args.get("host", "www.google.com")
|
|
|
|
status = subprocess.run(["ping", "-c", "1", "--", host]).returncode
|
|
return str(status == 0)
|
|
----
|
|
|
|
=== How does this work?
|
|
|
|
include::../../common/fix/introduction.adoc[]
|
|
|
|
include::../../common/fix/pre-approved-list.adoc[]
|
|
|
|
:sanitizationLib: subprocess
|
|
|
|
include::../../common/fix/sanitize-meta-characters.adoc[]
|
|
|
|
In the example compliant code, using the `subprocess.run` function helps to
|
|
escape the passed arguments. It accepts a list of command arguments that will
|
|
be properly escaped and concatenated to form the command line to execute.
|
|
|
|
include::../../common/fix/shell_integration.adoc[]
|
|
|
|
In the example compliant code, using the `subprocess` module's functions is
|
|
preferred over older alternative as the `os` or `popen` modules. Indeed,
|
|
`subprocess`, while still a dangerous library, disables the system shell's
|
|
syntax interpretation by default.
|