60 lines
1.7 KiB
Plaintext
60 lines
1.7 KiB
Plaintext
![]() |
Applications that execute operating system commands or execute commands that interact with the underlying system should neutralize any externally-provided values used in those commands. Failure to do so could allow an attacker to include input that executes unintended commands or exposes sensitive data.
|
||
|
|
||
|
The problem could be mitigated in any of the following ways:
|
||
|
* Using https://docs.python.org/3/library/subprocess.html[subprocess module] without the <code>shell=true</code>. In this case <code>subprocess</code> expects an array where command and arguments are clearly separated.
|
||
|
* Escaping shell argument with https://docs.python.org/3/library/shlex.html#shlex.quote[shlex.quote]
|
||
|
|
||
|
== Noncompliant Code Example
|
||
|
|
||
|
<code>os</code>
|
||
|
----
|
||
|
from flask import request
|
||
|
import os
|
||
|
|
||
|
@app.route('/ping')
|
||
|
def ping():
|
||
|
address = request.args.get("address")
|
||
|
cmd = "ping -c 1 %s" % address
|
||
|
os.popen(cmd) # Noncompliant
|
||
|
----
|
||
|
|
||
|
<code>subprocess</code>
|
||
|
----
|
||
|
from flask import request
|
||
|
import subprocess
|
||
|
|
||
|
@app.route('/ping')
|
||
|
def ping():
|
||
|
address = request.args.get("address")
|
||
|
cmd = "ping -c 1 %s" % address
|
||
|
subprocess.Popen(cmd, shell=True) # Noncompliant; using shell=true is unsafe
|
||
|
----
|
||
|
|
||
|
== Compliant Solution
|
||
|
|
||
|
<code>os</code>
|
||
|
----
|
||
|
from flask import request
|
||
|
import os
|
||
|
|
||
|
@app.route('/ping')
|
||
|
def ping():
|
||
|
address = shlex.quote(request.args.get("address")) # address argument is shell-escaped
|
||
|
cmd = "ping -c 1 %s" % address
|
||
|
os.popen(cmd ) # Compliant
|
||
|
----
|
||
|
|
||
|
<code>subprocess</code>
|
||
|
----
|
||
|
from flask import request
|
||
|
import subprocess
|
||
|
|
||
|
@app.route('/ping')
|
||
|
def ping():
|
||
|
address = request.args.get("address")
|
||
|
args = ["ping", "-c1", address]
|
||
|
subprocess.Popen(args) # Compliant
|
||
|
----
|
||
|
|
||
|
include::../see.adoc[]
|