我有一个LDAP查询,而我使用的执行在C#中进行搜索。它使用两个字符串变量(用户名和域名),这需要进行转义出于安全原因。
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.
我应该如何逃脱的琴弦?有没有在C#.NET中可用的功能来做到这一点?
How should I escape the strings? Is there a function available in C#.NET to do this?
例如LDAP搜索条件:
Example LDAP search conditions :
(objectCategory=person)
(userprincipalname=username@domain*)
(samaccountname=username)
在C#示例LDAP查询字符串:
Example LDAP query string in C# :
string search = "(&(&(objectCategory=person)(userprincipalname="
+ username
+ "@"
+ domain
+ "*)(samaccountname="
+ username
+ ")))";
编辑:我已经有LDAP查询工作,并返回结果。我想要的是逃避参数。
I already have the LDAP query working, and returning results. All I want is to escape the parameters.
以下是我从索菲亚提及到C#中的Java code翻译。
The following is my translation from the 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();
}