Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion python/ql/lib/semmle/python/frameworks/Flask.qll
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,10 @@ module Flask {
*/
module Blueprint {
/** Gets a reference to the `flask.Blueprint` class. */
API::Node classRef() { result = API::moduleImport("flask").getMember("Blueprint") }
API::Node classRef() {
result = API::moduleImport("flask").getMember("Blueprint") or
result = API::moduleImport("flask").getMember("blueprints").getMember("Blueprint")
}

/** Gets a reference to an instance of `flask.Blueprint`. */
API::Node instance() { result = classRef().getReturn() }
Expand Down
39 changes: 39 additions & 0 deletions python/ql/src/experimental/Security/CWE-073/AnyFileRead.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Desc :Any File Injection
"""
from flask import Flask, send_file, make_response
from flask import request
import os

filenames = ["/home/work/temp/a.png", "/home/work/temp/b.png"]

app = Flask(__name__)

@app.route('/bad1')
def bad1():
filename = request.args.get('filename')
context = send_file(filename, as_attachment=True) # Bad
return context

@app.route('/bad2')
def bad2():
filename = request.args.get('filename')
context = open(filename, 'r') # Bad
response = make_response(context)
return response

@app.route('/good1')
def good1():
filename = request.args.get('filename')
if filename in filenames: # Good
context = open(filename, 'r')
else:
context = "filename error"
response = make_response(context)
return response

if __name__ == '__main__':
app.debug = True
app.run()
38 changes: 38 additions & 0 deletions python/ql/src/experimental/Security/CWE-073/AnyFileRead.qhelp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>

<overview>
<p>
Accessing files using paths constructed from user-controlled data can allow an attacker to access
unexpected resources. This may cause sensitive information to be leaked
</p>
</overview>

<recommendation>
<p>
After the user completes the file path construction and before reading the file content, the file
path needs to be strictly verified.
</p>

</recommendation>

<example>
<p>
In the first and second examples, the accessed file name comes from the user's input, and without
any verification, it is directly returned to the user, causing the leakage of sensitive information.
For example: Linux system, the file name can enter <code>"/etc/passwd"</code> to obtain the system user password file.
</p>

<p>
In the third example, the file name entered by the user is fully verified, and there is no arbitrary file reading vulnerability.
</p>

<sample src="AnyFileRead.py" />
</example>

<references>
<li>OWASP: <a href="https://owasp.org/www-community/attacks/Path_Traversal">Path Traversal</a>.</li>
</references>
</qhelp>
20 changes: 20 additions & 0 deletions python/ql/src/experimental/Security/CWE-073/AnyFileRead.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @name Any File Read
* @description Accessing files using paths constructed by user-controlled data may allow attackers to access
* Unexpected resources, leading to leakage of sensitive information
* @kind path-problem
* @problem.severity error
* @precision high
* @id py/any-file-read
* @tags security
* external/cwe/cwe-073
*/

import python
import DataFlow::PathGraph
import AnyFileReadLib

from AnyFileReadFlowConfig config, DataFlow::PathNode source, DataFlow::PathNode sink
where config.hasFlowPath(source, sink)
select sink.getNode(), source, sink, "Any file read might include code from $@.", source.getNode(),
"this user input"
74 changes: 74 additions & 0 deletions python/ql/src/experimental/Security/CWE-073/AnyFileReadLib.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import python
import semmle.python.Concepts
import semmle.python.ApiGraphs
import semmle.python.dataflow.new.TaintTracking
import semmle.python.dataflow.new.TaintTracking2
import semmle.python.dataflow.new.RemoteFlowSources

/**
* A taint-tracking configuration for tracking untrusted user input used in file read.
*/
class AnyFileReadFlowConfig extends TaintTracking::Configuration {
AnyFileReadFlowConfig() { this = "AnyFileReadFlowConfig" }

override predicate isSource(DataFlow::Node source) { source instanceof RemoteFlowSource }

override predicate isSink(DataFlow::Node sink) { sink instanceof AnyFileReadSink }

override predicate isSanitizer(DataFlow::Node node) {
exists(Compare compare |
(
compare.getOp(0) instanceof In or
compare.getOp(0) instanceof NotIn
) and
compare.getLeft() = node.asExpr()
)
}
}

abstract private class FileReadCall extends DataFlow::CallCfgNode { }

private class FlaskSendFileCall extends FileReadCall {
FlaskSendFileCall() { this = API::moduleImport("flask").getMember("send_file").getACall() }
}

private class OpenReadCall extends FileReadCall {
OpenReadCall() {
(
this = API::builtin("open").getACall() or
this = API::moduleImport("io").getMember("open").getACall()
) and
this.getArg(1).asExpr().(StrConst).getText().toLowerCase().indexOf("r") > -1
}
}

/** A data flow sink for any file read vulnerabilities. */
class AnyFileReadSink extends DataFlow::Node {
AnyFileReadSink() {
exists(FileReadCall frc, DataFlow::Node pred | frc = pred |
frc.getArg(0) = this and
any(ResponseFlowConfig rfc).hasFlow(pred, _)
)
}
}

/**
* A taint-tracking configuration for file content to http response.
*/
private class ResponseFlowConfig extends TaintTracking2::Configuration {
ResponseFlowConfig() { this = "ResponseFlowConfig" }

override predicate isSource(DataFlow::Node source) { source instanceof FileReadCall }

override predicate isSink(DataFlow::Node sink) {
sink = any(HTTP::Server::HttpResponse hr).getBody()
}

override predicate isAdditionalTaintStep(DataFlow::Node node1, DataFlow::Node node2) {
exists(DataFlow::CallCfgNode call |
call = API::moduleImport("flask").getMember("make_response").getACall() and
call.getArg(0) = node1 and
call = node2
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
edges
| AnyFileRead.py:22:16:22:22 | ControlFlowNode for request | AnyFileRead.py:22:16:22:27 | ControlFlowNode for Attribute |
| AnyFileRead.py:22:16:22:27 | ControlFlowNode for Attribute | AnyFileRead.py:23:25:23:32 | ControlFlowNode for filename |
| AnyFileRead.py:28:16:28:22 | ControlFlowNode for request | AnyFileRead.py:28:16:28:27 | ControlFlowNode for Attribute |
| AnyFileRead.py:28:16:28:27 | ControlFlowNode for Attribute | AnyFileRead.py:29:20:29:27 | ControlFlowNode for filename |
| AnyFileRead.py:34:10:34:17 | ControlFlowNode for filename | AnyFileRead.py:38:30:38:38 | ControlFlowNode for file_path |
nodes
| AnyFileRead.py:22:16:22:22 | ControlFlowNode for request | semmle.label | ControlFlowNode for request |
| AnyFileRead.py:22:16:22:27 | ControlFlowNode for Attribute | semmle.label | ControlFlowNode for Attribute |
| AnyFileRead.py:23:25:23:32 | ControlFlowNode for filename | semmle.label | ControlFlowNode for filename |
| AnyFileRead.py:28:16:28:22 | ControlFlowNode for request | semmle.label | ControlFlowNode for request |
| AnyFileRead.py:28:16:28:27 | ControlFlowNode for Attribute | semmle.label | ControlFlowNode for Attribute |
| AnyFileRead.py:29:20:29:27 | ControlFlowNode for filename | semmle.label | ControlFlowNode for filename |
| AnyFileRead.py:34:10:34:17 | ControlFlowNode for filename | semmle.label | ControlFlowNode for filename |
| AnyFileRead.py:38:30:38:38 | ControlFlowNode for file_path | semmle.label | ControlFlowNode for file_path |
subpaths
#select
| AnyFileRead.py:23:25:23:32 | ControlFlowNode for filename | AnyFileRead.py:22:16:22:22 | ControlFlowNode for request | AnyFileRead.py:23:25:23:32 | ControlFlowNode for filename | Any file read might include code from $@. | AnyFileRead.py:22:16:22:22 | ControlFlowNode for request | this user input |
| AnyFileRead.py:29:20:29:27 | ControlFlowNode for filename | AnyFileRead.py:28:16:28:22 | ControlFlowNode for request | AnyFileRead.py:29:20:29:27 | ControlFlowNode for filename | Any file read might include code from $@. | AnyFileRead.py:28:16:28:22 | ControlFlowNode for request | this user input |
| AnyFileRead.py:38:30:38:38 | ControlFlowNode for file_path | AnyFileRead.py:34:10:34:17 | ControlFlowNode for filename | AnyFileRead.py:38:30:38:38 | ControlFlowNode for file_path | Any file read might include code from $@. | AnyFileRead.py:34:10:34:17 | ControlFlowNode for filename | this user input |
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Desc :Any File Injection
"""
from flask import Flask, send_file, make_response
from flask import request
from flask.blueprints import Blueprint
import os

blueprint = Blueprint('routes_general',
__name__,
static_folder='../static',
template_folder='../templates')

filenames = ["/home/work/temp/a.png", "/home/work/temp/b.png"]

app = Flask(__name__)

@app.route('/bad1')
def bad1():
filename = request.args.get('filename')
context = send_file(filename, as_attachment=True) # Bad
return context

@app.route('/bad2')
def bad2():
filename = request.args.get('filename')
context = open(filename, 'r') # Bad
response = make_response(context)
return response

@blueprint.route('/note_attachment/<filename>')
def bad3(filename):
file_path = os.path.join(PATH_NOTE_ATTACHMENTS, filename)
if file_path is not None:
try:
return send_file(file_path, as_attachment=True)
except Exception:
logger.exception("Send note attachment")

@app.route('/good1')
def good1():
filename = request.args.get('filename')
if filename in filenames: # Good
context = open(filename, 'r')
else:
context = "filename error"
response = make_response(context)
return response

if __name__ == '__main__':
app.debug = True
app.run()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
experimental/Security/CWE-073/AnyFileRead.ql