OWASP is a great resource for writing secure code, but some of there examples are outdated. For .Net, OWASP, as of this writing, recommends using LinqToAD (which appears to be outdated and no longer supported) or the AntiXSS tool which also appears to be outdated and a bit unreliable.
OWASP LDAP Injection Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html
A good example of how attacks on LDAP can occur via injection: https://www.synopsys.com/glossary/what-is-ldap-injection.html
In most cases, you probably just need to valid your input with a white list or a black list. White lists are always more secure than black lists, but if you are adding this check to an existing application you may prefer to start with a black list until you can identify and handle all the special characters you need to support.
Below is a bit of code I wrote to validate data against LDAP Injection risks. I found the Blacklist example here (https://stackoverflow.com/questions/53862391/how-does-ldapdistinguishednameencode-work-with-the-c-sharp-directoryservices-lib) and I added ‘|’, ‘(‘, and ‘)’ to it. Please let me know if you find an error in it!
using System.Text.RegularExpressions;
public class LDAPValidation
{
static readonly string whitelist = @"^[a-zA-Z\-\.']*$";
static Regex whiteListRegex = new Regex(whitelist);
public static bool IsNameValidForLdapQueryWhiteList(string strUserName)
{
strUserName = strUserName.Trim();
if (whiteListRegex.IsMatch(strUserName))
{
return true;
}
return false;
}
public static bool IsNameValidForLdapQueryBlackList(string strUserName, bool allowWildCard = false)
{
char[] illegalChars = { ',', '\\', '#', '+', '<', '>', ';', '"', '=', '|', '(', ')' };
if (strUserName.IndexOfAny(illegalChars) == -1)
{
if (allowWildCard == false && strUserName.Contains("*"))
return false;
return true;
}
return false;
}
public static void RunTests()
{
bool result = false;
result = IsNameValidForLdapQueryWhiteList("rkraft");
if (result == false) throw new Exception();
result = IsNameValidForLdapQueryWhiteList("*");
if (result == true) throw new Exception();
result = IsNameValidForLdapQueryWhiteList("#");
if (result == true) throw new Exception();
result = IsNameValidForLdapQueryBlackList("rkraft");
if (result == false) throw new Exception();
result = IsNameValidForLdapQueryBlackList("*");
if (result == true) throw new Exception();
result = IsNameValidForLdapQueryBlackList("#");
if (result == true) throw new Exception();
}
}