///
/// Escapes the LDAP search filter to prevent LDAP injection attacks.
///
///The search filter.
public static string EscapeLdapSearchFilterParam(string searchFilter) {
StringBuilder escape = new 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();
}
public bool Authenticate(string userName, string password) {
bool authentic = false;
try {
DirectoryEntry entry = new DirectoryEntry(this.LdapPath, userName, password);
object nativeObject = entry.NativeObject; authentic = true;
} catch (DirectoryServicesCOMException) { throw; }
return authentic;
}
public void ChangePassword(string userName, string currentPassword, string newPassword) {
try {
DirectoryEntry directionEntry = new DirectoryEntry(this.LdapPath, userName, currentPassword);
if (directionEntry != null) {
DirectorySearcher search = new DirectorySearcher(directionEntry);
search.Filter = "(SAMAccountName=" + EscapeLdapSearchFilterParam(userName) + ")";
SearchResult result = search.FindOne();
if (result != null) {
DirectoryEntry userEntry = result.GetDirectoryEntry();
if (userEntry != null) {
userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword });
userEntry.CommitChanges();
}
}
}
} catch (Exception ex) {
throw ex;
}
}
public void ResetPassword(string userDn, string password) {
DirectoryEntry uEntry = new DirectoryEntry(userDn);
uEntry.Invoke("SetPassword", new object[] { password });
uEntry.Properties["LockOutTime"].Value = 0;
//unlock account
uEntry.Close();
}
55100cookie-checkEscape ldap search filter / Active Directory