LDAP查询代码域用户CMD正常,系统权限CMD报0x80005000错误
问题描述
以下C#代码在域用户权限的CMD中可正常执行:
string strPath = "LDAP://" + dcip; DirectoryEntry de; if (String.IsNullOrEmpty(username)) { de = new DirectoryEntry(strPath); } else { de = new DirectoryEntry(strPath, username, password); } DirectorySearcher deSearch = new DirectorySearcher(de); deSearch.Filter = "(objectClass=domainDNS)"; deSearch.SearchScope = SearchScope.Subtree; SearchResult result = deSearch.FindOne(); return result.Properties["distinguishedName"][0].ToString();
但切换到系统权限的CMD中执行时,抛出如下COM异常:
System.Runtime.InteropServices.COMException (0x80005000): 未知错误(0x80005000) 在 System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) 在 System.DirectoryServices.DirectoryEntry.Bind() 在 System.DirectoryServices.DirectoryEntry.get_AdsObject() 在 System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne) 在 System.DirectoryServices.DirectorySearcher.FindOne()
而PowerView.ps1中实现相同逻辑的代码,却能在两种权限环境下均正常运行,需要解决该问题。
问题原因
系统权限对应的是本地系统账号(NT AUTHORITY\SYSTEM),默认创建DirectoryEntry时会使用当前上下文的机器账号(格式为DOMAIN\机器名$)进行LDAP绑定,但未指定适配系统权限的身份验证类型参数,导致绑定过程出现协议或权限层面的错误。而PowerView底层显式配置了适配该场景的LDAP绑定参数,因此可以正常执行。
解决方案
修改代码,在创建DirectoryEntry时显式指定身份验证类型,适配系统权限下的机器账号身份逻辑:
- 添加
AuthenticationTypes参数,推荐使用AuthenticationTypes.Secure | AuthenticationTypes.ServerBind组合,确保安全绑定并指定服务器端绑定模式; - 系统权限运行时无需传入用户名密码,直接使用机器账号上下文,但必须指定正确的验证类型。
修改后的代码示例:
using System.DirectoryServices; string strPath = "LDAP://" + dcip; DirectoryEntry de; AuthenticationTypes authType = AuthenticationTypes.Secure | AuthenticationTypes.ServerBind; if (String.IsNullOrEmpty(username)) { // 系统权限下使用当前机器账号上下文,指定验证类型 de = new DirectoryEntry(strPath, null, null, authType); } else { // 域用户权限下传入凭据,同时指定验证类型 de = new DirectoryEntry(strPath, username, password, authType); } DirectorySearcher deSearch = new DirectorySearcher(de); deSearch.Filter = "(objectClass=domainDNS)"; deSearch.SearchScope = SearchScope.Subtree; SearchResult result = deSearch.FindOne(); return result.Properties["distinguishedName"][0].ToString();
补充说明
AuthenticationTypes.Secure:启用SSL/TLS加密,保障LDAP通信安全;AuthenticationTypes.ServerBind:强制使用服务器端绑定模式,避免客户端绑定的兼容性问题,尤其适配系统权限场景;- 系统权限下的机器账号默认拥有域内基础LDAP查询权限,只要验证类型配置正确即可正常执行查询。
内容的提问来源于stack exchange,提问作者Szz9527
相关产品推荐
相关产品推荐

