2022-09-09 10:16:57 +02:00
|
|
|
=== How to fix it in .NET
|
|
|
|
|
2022-10-18 16:03:10 +02:00
|
|
|
The following noncompliant code is vulnerable to LDAP injections because untrusted data is
|
2022-09-09 10:16:57 +02:00
|
|
|
concatenated in an LDAP query without prior validation.
|
|
|
|
|
2022-10-18 16:03:10 +02:00
|
|
|
==== Noncompliant code example
|
2022-09-15 10:28:08 +02:00
|
|
|
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
2022-09-09 10:16:57 +02:00
|
|
|
----
|
|
|
|
public class ExampleController : Controller
|
|
|
|
{
|
|
|
|
public IActionResult Authenticate(string user, string pass)
|
|
|
|
{
|
|
|
|
DirectoryEntry directory = new DirectoryEntry("LDAP://ou=system");
|
|
|
|
DirectorySearcher search = new DirectorySearcher(directory);
|
|
|
|
|
2022-09-15 10:28:08 +02:00
|
|
|
search.Filter = "(&(uid=" + user + ")(userPassword=" + pass + "))";
|
2022-09-09 10:16:57 +02:00
|
|
|
|
|
|
|
return Json(search.FindOne() != null);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
2022-09-15 10:28:08 +02:00
|
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
2022-09-09 10:16:57 +02:00
|
|
|
----
|
|
|
|
public class ExampleController : Controller
|
|
|
|
{
|
|
|
|
public IActionResult Authenticate(string user, string pass)
|
|
|
|
{
|
|
|
|
// restrict the username and password to letters only
|
2022-09-15 10:41:27 +02:00
|
|
|
if (!Regex.IsMatch(user, "^[a-zA-Z]+$") || !Regex.IsMatch(pass, "^[a-zA-Z]+$"))
|
2022-09-09 10:16:57 +02:00
|
|
|
{
|
|
|
|
return BadRequest();
|
|
|
|
}
|
|
|
|
|
|
|
|
DirectoryEntry directory = new DirectoryEntry("LDAP://ou=system");
|
|
|
|
DirectorySearcher search = new DirectorySearcher(directory);
|
|
|
|
|
|
|
|
search.Filter = "(&(uid=" + user + ")(userPassword=" + pass + "))";
|
|
|
|
|
|
|
|
return Json(search.FindOne() != null);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
=== How does this work?
|
|
|
|
|
|
|
|
include::../../common/fix/validation.adoc[]
|
|
|
|
|
|
|
|
In the compliant solution example, a validation mechanism is applied to untrusted input to ensure
|
|
|
|
it is strictly composed of alphabetic characters.
|