[ACCEPTED]-How to escape a string in C#, for use in an LDAP query-ldap-query

Accepted answer
Score: 33

The following is my translation from the 1 Java code mentioned by Sophia into C#.

/// <summary>
/// Escapes the LDAP search filter to prevent LDAP injection attacks.
/// </summary>
/// <param name="searchFilter">The search filter.</param>
/// <see cref="https://blogs.oracle.com/shankar/entry/what_is_ldap_injection" />
/// <see cref="http://msdn.microsoft.com/en-us/library/aa746475.aspx" />
/// <returns>The escaped search filter.</returns>
private static string EscapeLdapSearchFilter(string searchFilter)
{
    StringBuilder escape = new StringBuilder(); // If using JDK >= 1.5 consider using StringBuilder
    for (int i = 0; i < searchFilter.Length; ++i)
    {
        char current = searchFilter[i];
        switch (current)
        {
            case '\\':
                escape.Append(@"\5c");
                break;
            case '*':
                escape.Append(@"\2a");
                break;
            case '(':
                escape.Append(@"\28");
                break;
            case ')':
                escape.Append(@"\29");
                break;
            case '\u0000':
                escape.Append(@"\00");
                break;
            case '/':
                escape.Append(@"\2f");
                break;
            default:
                escape.Append(current);
                break;
        }
    }

    return escape.ToString();
}
Score: 6

I found a solution here, in a blog post about LDAP Injection

This solution 9 involves adding your own function to escape 8 the username and domain name, his solution 7 is in Java, but the idea is there.

Also MSDN lists 6 which special characters need to be replaced 5 by escape sequences.

As far as I can tell 4 there doesn't seem to be any method for 3 escaping LDAP strings in System.DirectoryServices 2 (like there is in HttpServerUtility for 1 URLs etc)

Score: 4

Use AntiXss library from address: https://www.nuget.org/packages/AntiXss

string encoded = Microsoft.Security.Application.Encoder.LdapFilterEncode(input);

0

Score: 2

Maybe let somebody else worry about it? See 1 LINQtoAD.

Score: 2

Are you trying to prevent some sort of injection 4 attack against your directory server via 3 user input? If that is the case I would 2 just validate the input with Regex before 1 passing it to LDAP.

Score: 0

Use PInvoke with DsQuoteRdnValueW. For code, see my answer 1 to another question: https://stackoverflow.com/a/11091804/628981

More Related questions