An LDAP query that relies on potentially untrusted inputs might allow attackers to inject unwanted elements into the query. This can allow attackers to read or modify sensitive data, run code, and perform other unwanted actions.
1public void ldapSearchNoncompliant(HttpServletRequest request) {
2 try {
3 DirContext directoryContext = new InitialDirContext();
4 SearchControls controls = new SearchControls();
5 final String filter = request.getParameter("filter");
6 Object[] args = new Object[]{"Some object"};
7 String base = "some base";
8 // Noncompliant: unsanitized user-supplied filter is used.
9 NamingEnumeration<SearchResult> results =
10 directoryContext.search(base, filter, args, controls);
11 System.out.println(results);
12 } catch (NamingException e) {
13 System.out.println(e);
14 }
15}
1public void ldapSearchCompliant(HttpServletRequest request) {
2 try {
3 DirContext directoryContext = new InitialDirContext();
4 SearchControls controls = new SearchControls();
5 final String filter = request.getParameter("filter");
6 // Compliant: user-supplied filter is checked for allowed characters to prevent ldap injection.
7 if (!filter.matches("[a-z]+")) {
8 throw new IllegalArgumentException();
9 }
10 Object[] args = new Object[]{"Some object"};
11 String base = "some base";
12 NamingEnumeration<SearchResult> results =
13 directoryContext.search(base, filter, args, controls);
14 System.out.println(results);
15 } catch (NamingException e) {
16 System.out.println(e);
17 }
18}