# 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.

a drawn cute bird pointing at a graph that shows positive results

# Properties

Property Value
Rule ID UseParameterizedLDAPQuery
First seen in jSparrow version 3.19.0
Minimum Java version 1.3
Remediation cost 30 min
Links