54 lines
1.5 KiB
Plaintext
Raw Normal View History

=== 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
concatenated in an LDAP query without prior validation.
2022-10-18 16:03:10 +02:00
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
public class ExampleController : Controller
{
public IActionResult Authenticate(string user, string pass)
{
DirectoryEntry directory = new DirectoryEntry("LDAP://ou=system");
DirectorySearcher search = new DirectorySearcher(directory);
search.Filter = "(&(uid=" + user + ")(userPassword=" + pass + "))";
return Json(search.FindOne() != null);
}
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
public class ExampleController : Controller
{
public IActionResult Authenticate(string user, string pass)
{
// restrict the username and password to letters only
if (!Regex.IsMatch(user, "^[a-zA-Z]+$") || !Regex.IsMatch(pass, "^[a-zA-Z]+$"))
{
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.