== How to fix it in .NET

=== Code examples

The following noncompliant code is vulnerable to LDAP injections because untrusted data is
concatenated in an LDAP query without prior validation.

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