Code injection¶
ID: py/code-injectionKind: path-problemSecurity severity: 9.3Severity: errorPrecision: highTags: - security - external/cwe/cwe-094 - external/cwe/cwe-095 - external/cwe/cwe-116Query suites: - python-code-scanning.qls - python-security-extended.qls - python-security-and-quality.qls
Click to see the query in the CodeQL repository
Directly evaluating user input (for example, an HTTP request parameter) as code without properly sanitizing the input first allows an attacker arbitrary code execution. This can occur when user input is passed to code that interprets it as an expression to be evaluated, such aseval orexec.
Recommendation¶
Avoid including user input in any expression that may be dynamically evaluated. If user input must be included, use context-specific escaping before including it. It is important that the correct escaping is used for the type of evaluation that will occur.
Example¶
The following example shows two functions setting a name from a request. The first function usesexec to execute thesetname function. This is dangerous as it can allow a malicious user to execute arbitrary code on the server. For example, the user could supply the value"'+subprocess.call('rm-rf')+'" to destroy the server’s file system. The second function calls thesetname function directly and is thus safe.
urlpatterns=[# Route to code_executionurl(r'^code-ex1$',code_execution_bad,name='code-execution-bad'),url(r'^code-ex2$',code_execution_good,name='code-execution-good')]defcode_execution(request):ifrequest.method=='POST':first_name=base64.decodestring(request.POST.get('first_name',''))#BAD -- Allow user to define code to be run.exec("setname('%s')"%first_name)defcode_execution(request):ifrequest.method=='POST':first_name=base64.decodestring(request.POST.get('first_name',''))#GOOD --Call code directlysetname(first_name)
References¶
OWASP:Code Injection.
Wikipedia:Code Injection.
Common Weakness Enumeration:CWE-94.
Common Weakness Enumeration:CWE-95.
Common Weakness Enumeration:CWE-116.