I have an LDAP query, which I am using to perform a search in C#. It uses two string variables (username and domain) which need to be escaped for security reasons.
How should I escape the strings? Is there a function available in C#.NET to do this?
Example LDAP search conditions :
(objectCategory=person)
(userprincipalname=username@domain*)
(samaccountname=username)
Example LDAP query string in C# :
string search = "(&(&(objectCategory=person)(userprincipalname="
+ username
+ "@"
+ domain
+ "*)(samaccountname="
+ username
+ ")))";
Edit: I already have the LDAP query working, and returning results. All I want is to escape the parameters.
I found a solution here, in a blog post about LDAP Injection
This solution involves adding your own function to escape the username and domain name, his solution is in Java, but the idea is there.
Also MSDN lists which special characters need to be replaced by escape sequences.
As far as I can tell there doesn't seem to be any method for escaping LDAP strings in System.DirectoryServices (like there is in HttpServerUtility for URLs etc)
Maybe let somebody else worry about it? See LINQtoAD.
Use AntiXss library from address: https://www.nuget.org/packages/AntiXss
The following is my translation from the Java code mentioned by Sophia into C#.
Are you trying to prevent some sort of injection attack against your directory server via user input? If that is the case I would just validate the input with Regex before passing it to LDAP.
Use PInvoke with
DsQuoteRdnValueW
. For code, see my answer to another question: https://stackoverflow.com/a/11091804/628981