# 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());
Use a Java Refactoring Tool
No license required
You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.
System-wide Refactoring
Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.