Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
799d509
Upload LDAP Injection query, qhelp and tests
jorgectf Mar 18, 2021
719b48c
Move to experimental folder
jorgectf Mar 18, 2021
95a1dae
Precision warn and Remove CWE reference
jorgectf Mar 18, 2021
85ec82a
Refactor in progress
jorgectf Mar 28, 2021
ad36bea
Refactor LDAP3 stuff (untested)
jorgectf Mar 29, 2021
8223539
Add a test without attributes
jorgectf Mar 29, 2021
3cda2e5
Polish up ldap3 tests
jorgectf Mar 29, 2021
8faafb6
Update Sink
jorgectf Mar 30, 2021
4328ff3
Remove attrs feature
jorgectf Mar 31, 2021
9b43031
Improve Sanitizer calls
jorgectf Mar 31, 2021
1bcb9cd
Simplify query
jorgectf Apr 6, 2021
33423ea
Optimize calls
jorgectf Apr 7, 2021
a1850dd
Change LDAP config (qll) filename
jorgectf Apr 8, 2021
8661cb0
Polish LDAP3Query
jorgectf Apr 8, 2021
7296879
Polish tests
jorgectf Apr 8, 2021
3c1ca72
Improve qhelp
jorgectf Apr 8, 2021
1554f4f
Create qhelp examples
jorgectf Apr 8, 2021
95bfdc4
Move tests to /test
jorgectf Apr 8, 2021
4f85de8
Add qlref
jorgectf Apr 8, 2021
7819d1a
Generate .expected
jorgectf Apr 8, 2021
b405c67
Add qhelp last newline
jorgectf Apr 8, 2021
82f47f8
Polish metadata
jorgectf Apr 8, 2021
cd75433
Fix qhelp examples extension
jorgectf Apr 8, 2021
a2e8d88
Write documentation
jorgectf Apr 8, 2021
b020ea6
Polish documentation
jorgectf Apr 8, 2021
1c34230
Fix documentation typo
jorgectf Apr 8, 2021
c2b96b3
Add documentation to main classes' functions.
jorgectf May 7, 2021
34b8af3
Move structure to LDAP.qll
jorgectf May 7, 2021
6159fbe
Update functions naming
jorgectf May 7, 2021
2ad72ad
Add LDAP framework entry in Frameworks.qll
jorgectf May 7, 2021
8665747
Update sink and sanitizer to match new naming
jorgectf May 8, 2021
9e9678b
Apply documentation suggestions
jorgectf May 21, 2021
37d6ff7
Update tests and .expected
jorgectf May 21, 2021
d5f2846
Merge branch 'main' into jorgectf/python/ldapInjection
RasmusWL May 26, 2021
f807c2f
Python: autoformat
RasmusWL May 26, 2021
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
50 changes: 50 additions & 0 deletions python/ql/src/experimental/Security/CWE-090/LDAPInjection.qhelp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>If an LDAP query or DN is built using string concatenation or string formatting, and the
components of the concatenation include user input without any proper sanitization, a user
is likely to be able to run malicious LDAP queries.</p>
</overview>

<recommendation>
<p>If user input must be included in an LDAP query or DN, it should be escaped to
avoid a malicious user providing special characters that change the meaning
of the query. In Python2, user input should be escaped with <code>ldap.dn.escape_dn_chars</code>
or <code>ldap.filter.escape_filter_chars</code>, while in Python3, user input should be escaped with
<code>ldap3.utils.dn.escape_rdn</code> or <code>ldap3.utils.conv.escape_filter_chars</code>
depending on the component tainted by the user. A good practice is to escape filter characters
that could change the meaning of the query (https://tools.ietf.org/search/rfc4515#section-3).</p>
</recommendation>

<example>
<p>In the following examples, the code accepts both <code>username</code> and <code>dc</code> from the user,
which it then uses to build a LDAP query and DN.</p>

<p>The first and the second example uses the unsanitized user input directly
in the search filter and DN for the LDAP query.
A malicious user could provide special characters to change the meaning of these
components, and search for a completely different set of values.</p>

<sample src="examples/example_bad1.js" />
<sample src="examples/example_bad2.js" />

<p>In the third and four example, the input provided by the user is sanitized before it is included in the search filter or DN.
This ensures the meaning of the query cannot be changed by a malicious user.</p>

<sample src="examples/example_good1.js" />
<sample src="examples/example_good2.js" />
</example>

<references>
<li>OWASP: <a href="https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html">LDAP Injection Prevention Cheat Sheet</a>.</li>
<li>OWASP: <a href="https://owasp.org/www-community/attacks/LDAP_Injection">LDAP Injection</a>.</li>
<li>SonarSource: <a href="https://rules.sonarsource.com/python/RSPEC-2078">RSPEC-2078</a>.</li>
<li>Python2: <a href="https://www.python-ldap.org/en/python-ldap-3.3.0/reference/ldap.html">LDAP Documentation</a>.</li>
<li>Python3: <a href="https://ldap3.readthedocs.io/en/latest/">LDAP Documentation</a>.</li>
<li>Wikipedia: <a href="https://en.wikipedia.org/wiki/LDAP_injection">LDAP injection</a>.</li>
<li>BlackHat: <a href="https://www.blackhat.com/presentations/bh-europe-08/Alonso-Parada/Whitepaper/bh-eu-08-alonso-parada-WP.pdf">LDAP Injection and Blind LDAP Injection</a>.</li>
<li>LDAP: <a href="https://ldap.com/2018/05/04/understanding-and-defending-against-ldap-injection-attacks/">Understanding and Defending Against LDAP Injection Attacks</a>.</li>
</references>
</qhelp>
20 changes: 20 additions & 0 deletions python/ql/src/experimental/Security/CWE-090/LDAPInjection.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @name Python LDAP Injection
* @description Python LDAP Injection through search filter
* @kind path-problem
* @problem.severity error
* @id python/ldap-injection
* @tags experimental
* security
* external/cwe/cwe-090
*/

// Determine precision above
import python
import experimental.semmle.python.security.injection.LDAP
import DataFlow::PathGraph

from LDAPInjectionFlowConfig config, DataFlow::PathNode source, DataFlow::PathNode sink
where config.hasFlowPath(source, sink)
select sink.getNode(), source, sink, "$@ LDAP query parameter comes from $@.", sink.getNode(),
"This", source.getNode(), "a user-provided value"
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from flask import request, Flask
import ldap


@app.route("/normal")
def normal():
unsafe_dn = "dc=%s" % request.args['dc']
unsafe_filter = "(user=%s)" % request.args['username']

ldap_connection = ldap.initialize("ldap://127.0.0.1:1337")
user = ldap_connection.search_s(
unsafe_dn, ldap.SCOPE_SUBTREE, unsafe_filter)
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from flask import request, Flask
import ldap3


@app.route("/normal")
def normal():
unsafe_dn = "dc=%s" % request.args['dc']
unsafe_filter = "(user=%s)" % request.args['username']

srv = ldap3.Server('ldap://127.0.0.1', port=1337)
conn = ldap3.Connection(srv, user=unsafe_dn, auto_bind=True)
conn.search(unsafe_dn, unsafe_filter)
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from flask import request, Flask
import ldap
import ldap.filter
import ldap.dn


@app.route("/normal")
def normal():
unsafe_dn = "dc=%s" % request.args['dc']
unsafe_filter = "(user=%s)" % request.args['username']

safe_dn = ldap.dn.escape_dn_chars(unsafe_dn)
safe_filter = ldap.filter.escape_filter_chars(unsafe_filter)

ldap_connection = ldap.initialize("ldap://127.0.0.1:1337")
user = ldap_connection.search_s(
safe_dn, ldap.SCOPE_SUBTREE, safe_filter)
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from flask import request, Flask
import ldap3
from ldap3.utils.dn import escape_rdn
from ldap3.utils.conv import escape_filter_chars


@app.route("/normal")
def normal():
unsafe_dn = "dc=%s" % request.args['dc']
unsafe_filter = "(user=%s)" % request.args['username']

safe_dn = escape_rdn(unsafe_dn)
safe_filter = escape_filter_chars(unsafe_filter)

srv = ldap3.Server('ldap://127.0.0.1', port=1337)
conn = ldap3.Connection(srv, user=safe_dn, auto_bind=True)
conn.search(safe_dn, safe_filter)
28 changes: 28 additions & 0 deletions python/ql/src/experimental/semmle/python/Concepts.qll
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,31 @@ private import semmle.python.dataflow.new.DataFlow
private import semmle.python.dataflow.new.RemoteFlowSources
private import semmle.python.dataflow.new.TaintTracking
private import experimental.semmle.python.Frameworks

module LDAPQuery {
abstract class Range extends DataFlow::Node {
abstract DataFlow::Node getLDAPNode();
}
}

class LDAPQuery extends DataFlow::Node {
LDAPQuery::Range range;

LDAPQuery() { this = range }

DataFlow::Node getLDAPNode() { result = range.getLDAPNode() }
}

module LDAPEscape {
abstract class Range extends DataFlow::Node {
abstract DataFlow::Node getEscapeNode();
}
}

class LDAPEscape extends DataFlow::Node {
LDAPEscape::Range range;

LDAPEscape() { this = range }

DataFlow::Node getEscapeNode() { result = range.getEscapeNode() }
}
97 changes: 97 additions & 0 deletions python/ql/src/experimental/semmle/python/frameworks/Stdlib.qll
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,100 @@ private import semmle.python.dataflow.new.TaintTracking
private import semmle.python.dataflow.new.RemoteFlowSources
private import experimental.semmle.python.Concepts
private import semmle.python.ApiGraphs

private module LDAP {
private module LDAP2 {
private class LDAP2QueryMethods extends string {
LDAP2QueryMethods() {
this in ["search", "search_s", "search_st", "search_ext", "search_ext_s"]
}
}

private class LDAP2Query extends DataFlow::CallCfgNode, LDAPQuery::Range {
DataFlow::Node ldapNode;

LDAP2Query() {
exists(DataFlow::AttrRead searchMethod |
this.getFunction() = searchMethod and
API::moduleImport("ldap").getMember("initialize").getACall() =
searchMethod.getObject().getALocalSource() and
searchMethod.getAttributeName() instanceof LDAP2QueryMethods and
(
ldapNode = this.getArg(0)
or
(
ldapNode = this.getArg(2) or
ldapNode = this.getArgByName("filterstr")
)
)
)
}

override DataFlow::Node getLDAPNode() { result = ldapNode }
}

private class LDAP2EscapeDNCall extends DataFlow::CallCfgNode, LDAPEscape::Range {
LDAP2EscapeDNCall() {
this = API::moduleImport("ldap").getMember("dn").getMember("escape_dn_chars").getACall()
}

override DataFlow::Node getEscapeNode() { result = this.getArg(0) }
}

private class LDAP2EscapeFilterCall extends DataFlow::CallCfgNode, LDAPEscape::Range {
LDAP2EscapeFilterCall() {
this =
API::moduleImport("ldap").getMember("filter").getMember("escape_filter_chars").getACall()
}

override DataFlow::Node getEscapeNode() { result = this.getArg(0) }
}
}

private module LDAP3 {
private class LDAP3Query extends DataFlow::CallCfgNode, LDAPQuery::Range {
DataFlow::Node ldapNode;

LDAP3Query() {
exists(DataFlow::AttrRead searchMethod |
this.getFunction() = searchMethod and
API::moduleImport("ldap3").getMember("Connection").getACall() =
searchMethod.getObject().getALocalSource() and
searchMethod.getAttributeName() = "search" and
(
ldapNode = this.getArg(0) or
ldapNode = this.getArg(1)
)
)
}

override DataFlow::Node getLDAPNode() { result = ldapNode }
}

private class LDAP3EscapeDNCall extends DataFlow::CallCfgNode, LDAPEscape::Range {
LDAP3EscapeDNCall() {
this =
API::moduleImport("ldap3")
.getMember("utils")
.getMember("dn")
.getMember("escape_rdn")
.getACall()
}

override DataFlow::Node getEscapeNode() { result = this.getArg(0) }
}

private class LDAP3EscapeFilterCall extends DataFlow::CallCfgNode, LDAPEscape::Range {
LDAP3EscapeFilterCall() {
this =
API::moduleImport("ldap3")
.getMember("utils")
.getMember("conv")
.getMember("escape_filter_chars")
.getACall()
}

override DataFlow::Node getEscapeNode() { result = this.getArg(0) }
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Provides a taint-tracking configuration for detecting LDAP injection vulnerabilities
*/

import python
import experimental.semmle.python.Concepts
import semmle.python.dataflow.new.DataFlow
import semmle.python.dataflow.new.TaintTracking
import semmle.python.dataflow.new.RemoteFlowSources

/**
* A taint-tracking configuration for detecting regular expression injections.
*/
class LDAPInjectionFlowConfig extends TaintTracking::Configuration {
LDAPInjectionFlowConfig() { this = "LDAPInjectionFlowConfig" }

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

override predicate isSink(DataFlow::Node sink) { sink = any(LDAPQuery ldapQuery).getLDAPNode() }

override predicate isSanitizer(DataFlow::Node sanitizer) {
sanitizer = any(LDAPEscape ldapEsc).getEscapeNode()
}
}
Loading