# Use Parameterized LDAP Query
# Description
Similar to SQL queries, the LDAP (opens new window) search filters are also vulnerable to injection attacks. This rule parameterizes all potential user supplied input that are concatenated into an LDAP search filter. For example, the invocations of DirContext::search(Name name, String filter, SearchControls cons) (opens new window) are replaced by DirContext::search(Name name, String filter, Object[] args, SearchControls cons) (opens new window) where the filter concatenation fragments are extracted into an Object array.
# Benefits
Prevents injections when using Lightweight Directory Access Protocol (LDAP).
# Tags
# Code Changes
# Using a String variable as filter
Pre
String userId = "*)(uid=*))(|(uid=*";
String userPassword = "password";
DirContext ctx = getDirContext();
String filter = "(&(uid=" + userId + ")(userPassword=" + userPassword + "))";
NamingEnumeration<SearchResult> results = ctx.search(
"ou=system",
filter,
new SearchControls());
Post
String userId = "*)(uid=*))(|(uid=*";
String userPassword = "password";
DirContext ctx = getDirContext();
String filter = "(&(uid={0}" + ")(userPassword={1}" + "))";
NamingEnumeration<SearchResult> results = ctx.search(
"ou=system",
filter,
new Object[] { userId, userPassword },
new SearchControls());
# Using a String concatenation expression as filter
Pre
String userId = "*)(uid=*))(|(uid=*";
String userPassword = "password";
DirContext ctx = getDirContext();
NamingEnumeration<SearchResult> results = ctx.search(
"ou=system",
"(&(uid=" + userId + ")(userPassword=" + userPassword + "))",
new SearchControls());
Post
String userId = "*)(uid=*))(|(uid=*";
String userPassword = "password";
DirContext ctx = getDirContext();
NamingEnumeration<SearchResult> results = ctx.search(
"ou=system",
"(&(uid={0}" + ")(userPassword={1}" + "))",
new Object[] { userId, userPassword },
new SearchControls());
🛠️ Auto-refactor Available
You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:
Need help? Check out our installation guide.