/// <summary> /// Disposes of this LSA wrapper /// </summary> public void Dispose() { if (lsaHandle != IntPtr.Zero) { Win32Sec.LsaClose(lsaHandle); lsaHandle = IntPtr.Zero; } GC.SuppressFinalize(this); }
/// <summary> /// Creates a new LSA wrapper for the specified MachineName /// </summary> /// <param name="MachineName">The name of the machine that should be connected to</param> public LsaWrapper(string MachineName) { LSA_OBJECT_ATTRIBUTES lsaAttr; lsaAttr.RootDirectory = IntPtr.Zero; lsaAttr.ObjectName = IntPtr.Zero; lsaAttr.Attributes = 0; lsaAttr.SecurityDescriptor = IntPtr.Zero; lsaAttr.SecurityQualityOfService = IntPtr.Zero; lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES)); lsaHandle = IntPtr.Zero; LSA_UNICODE_STRING[] system = null; if (MachineName != null) { system = new LSA_UNICODE_STRING[1]; system[0] = InitLsaString(MachineName); } uint ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr, (int)Access.POLICY_ALL_ACCESS, out lsaHandle); TestReturnValue(ret); }
/// <summary> /// Tests the return value from Win32 method calls /// </summary> /// <param name="ReturnValue">The return value from the a Win32 method call</param> private void TestReturnValue(uint ReturnValue) { if (ReturnValue == 0) { return; } if (ReturnValue == ERROR_PRIVILEGE_DOES_NOT_EXIST) { return; } if (ReturnValue == ERROR_NO_MORE_ITEMS) { return; } if (ReturnValue == STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } if ((ReturnValue == STATUS_INSUFFICIENT_RESOURCES) || (ReturnValue == STATUS_NO_MEMORY)) { throw new OutOfMemoryException(); } throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ReturnValue)); }
/// <summary> /// Reads the user accounts which have the specific privilege /// </summary> /// <param name="Privilege">The name of the privilege for which the accounts with this right should be enumerated</param> public List <String> ReadPrivilege(string Privilege) { LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1]; privileges[0] = InitLsaString(Privilege); IntPtr buffer; int count = 0; uint ret = Win32Sec.LsaEnumerateAccountsWithUserRight(lsaHandle, privileges, out buffer, out count); List <String> Accounts = new List <String>(); if (ret == 0) { LSA_ENUMERATION_INFORMATION[] LsaInfo = new LSA_ENUMERATION_INFORMATION[count]; for (int i = 0, elemOffs = (int)buffer; i < count; i++) { LsaInfo[i] = (LSA_ENUMERATION_INFORMATION)Marshal.PtrToStructure((IntPtr)elemOffs, typeof(LSA_ENUMERATION_INFORMATION)); elemOffs += Marshal.SizeOf(typeof(LSA_ENUMERATION_INFORMATION)); SecurityIdentifier SID = new SecurityIdentifier(LsaInfo[i].PSid); Accounts.Add(ResolveAccountName(SID)); } return(Accounts); } TestReturnValue(ret); return(Accounts); }