Accessing the LSA from managed code
October 10, 2010 5 Comments
This blog entry would be filed under the ‘it should not be this hard’ category if I had one. A reasonably common requirement is to determine the rights a user has and then to add additional rights as necessary. After much searching I could not find a ‘managed’ way to do this so I ended up with the following…
This post very much stands on the shoulders of others and so here are the links to the original articles I used:
• LSA .NET from Code Project
• “RE: Unmarshalling LsaEnumerateAccountRights() list of privileges”
When installing a new service, it is often necessary to add additional rights to the user that the service runs as, for example ‘Log on a service’. To do so from either managed code or PowerShell would seem like a reasonably obvious ask but I could not find any type that allowed me to. The security information is managed by the Local Security Authority (LSA) which has an unmanaged API available from advapi32.dll, to access this from C# requires P/Invoke and a reasonable amount of code to marshall the types. I’m not a C++ programmer and so I first looked for an alternative.
The Windows Server 2003 Resource Kit includes a utility NTRights.exe which allows rights to be added and removed from a user via the command line. Unfortunately this tool no longer ships in the Windows Server 2008 Resource Kit but the 2003 version still works on both Windows 7 and Server 2008 (R2). The tool provided part of the solution but I also wanted to be able to find out the rights that have already been assigned to the user as well as add and remove.
No matter which way I turned, I was always led back to the advapi32 and writing a wrapper to allow the functions to be called from C#. Thankfully most of the hard work had already been done and documented by Corinna John, with a sample project posted on Code Project. The original article comes from 2003, so I was a little surprised that it still hasn’t made it into a managed library. The sample by Corinna showed show to add rights to a user but unfortunately did not include listing the rights. For that I have to thank Seng who lists sample code here.
By combining the efforts of both together and cleaning up the code a little I ended up with the wrapper class given at the end of the posting (there is plenty of room for improvement in my code). This was compiled in VS2010, the API ended up as:
public IList GetRights(string accountName) public void SetRight(string accountName, string privilegeName) public void SetRights(string accountName, IList rights)
I had to compile for .NET 2.0 so that I could call it from PowerShell…
[void][Reflection.Assembly]::LoadFile('C:\Samples\LSAController.dll') # void suppresses the output of the message text $LsaController = New-Object -TypeName 'LSAController.LocalSecurityAuthorityController' $LsaRights = New-Object -TypeName 'LSAController.LocalSecurityAuthorityRights' # a convenience class containing common rights $LsaController.SetRight('ADERANT_AP\stefan.sewell', [LSAController.LocalSecurityAuthorityRights]::LogonAsBatchJob) $LsaController.GetRights('ADERANT_AP\stefan.sewell')
The code for the wrapper follows, I hope this saves someone the 2 days I spend on this.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; // // This code has been adapted from http://www.codeproject.com/KB/cs/lsadotnet.aspx // The rights enumeration code came from http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.interop/2004-11/0394.html // // Windows Security via .NET is covered on by Pluralsight:http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook/HomePage.html // namespace LSAController { // // Provides methods the local security authority which controls user rights. Managed via secpol.msc normally. // public class LocalSecurityAuthorityController { private const int Access = (int)( LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN | LSA_AccessPolicy.POLICY_CREATE_ACCOUNT | LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE | LSA_AccessPolicy.POLICY_CREATE_SECRET | LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION | LSA_AccessPolicy.POLICY_LOOKUP_NAMES | LSA_AccessPolicy.POLICY_NOTIFICATION | LSA_AccessPolicy.POLICY_SERVER_ADMIN | LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS | LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS | LSA_AccessPolicy.POLICY_TRUST_ADMIN | LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION | LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION ); [DllImport("advapi32.dll", PreserveSig = true)] private static extern UInt32 LsaOpenPolicy(ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, Int32 DesiredAccess, out IntPtr PolicyHandle); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern int LsaAddAccountRights(IntPtr PolicyHandle, IntPtr AccountSid, LSA_UNICODE_STRING[] UserRights, int CountOfRights); [DllImport("advapi32")] public static extern void FreeSid(IntPtr pSid); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, PreserveSig = true)] private static extern bool LookupAccountName(string lpSystemName, string lpAccountName, IntPtr psid, ref int cbsid, StringBuilder domainName, ref int cbdomainLength, ref int use); [DllImport("advapi32.dll")] private static extern bool IsValidSid(IntPtr pSid); [DllImport("advapi32.dll")] private static extern int LsaClose(IntPtr ObjectHandle); [DllImport("kernel32.dll")] private static extern int GetLastError(); [DllImport("advapi32.dll")] private static extern int LsaNtStatusToWinError(int status); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern int LsaEnumerateAccountRights(IntPtr PolicyHandle, IntPtr AccountSid, out IntPtr UserRightsPtr, out int CountOfRights); [StructLayout(LayoutKind.Sequential)] private struct LSA_UNICODE_STRING { public UInt16 Length; public UInt16 MaximumLength; public IntPtr Buffer; } [StructLayout(LayoutKind.Sequential)] private struct LSA_OBJECT_ATTRIBUTES { public int Length; public IntPtr RootDirectory; public LSA_UNICODE_STRING ObjectName; public UInt32 Attributes; public IntPtr SecurityDescriptor; public IntPtr SecurityQualityOfService; } [Flags] private enum LSA_AccessPolicy : long { POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L, POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L, POLICY_GET_PRIVATE_INFORMATION = 0x00000004L, POLICY_TRUST_ADMIN = 0x00000008L, POLICY_CREATE_ACCOUNT = 0x00000010L, POLICY_CREATE_SECRET = 0x00000020L, POLICY_CREATE_PRIVILEGE = 0x00000040L, POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L, POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L, POLICY_AUDIT_LOG_ADMIN = 0x00000200L, POLICY_SERVER_ADMIN = 0x00000400L, POLICY_LOOKUP_NAMES = 0x00000800L, POLICY_NOTIFICATION = 0x00001000L } // Returns the Local Security Authority rights granted to the account public IList<string> GetRights(string accountName) { IList<string> rights = new List<string>(); string errorMessage = string.Empty; long winErrorCode = 0; IntPtr sid = IntPtr.Zero; int sidSize = 0; StringBuilder domainName = new StringBuilder(); int nameSize = 0; int accountType = 0; LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType); domainName = new StringBuilder(nameSize); sid = Marshal.AllocHGlobal(sidSize); if (!LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType)) { winErrorCode = GetLastError(); errorMessage = ("LookupAccountName failed: " + winErrorCode); } else { LSA_UNICODE_STRING systemName = new LSA_UNICODE_STRING(); IntPtr policyHandle = IntPtr.Zero; IntPtr userRightsPtr = IntPtr.Zero; int countOfRights = 0; LSA_OBJECT_ATTRIBUTES objectAttributes = CreateLSAObject(); uint policyStatus = LsaOpenPolicy(ref systemName, ref objectAttributes, Access, out policyHandle); winErrorCode = LsaNtStatusToWinError(Convert.ToInt32(policyStatus)); if (winErrorCode != 0) { errorMessage = string.Format("OpenPolicy failed: {0}.", winErrorCode); } else { int result = LsaEnumerateAccountRights(policyHandle, sid, out userRightsPtr, out countOfRights); winErrorCode = LsaNtStatusToWinError(result); if (winErrorCode != 0) { errorMessage = string.Format("LsaAddAccountRights failed: {0}", winErrorCode); } Int32 ptr = userRightsPtr.ToInt32(); LSA_UNICODE_STRING userRight; for (int i = 0; i < countOfRights; i++) { userRight = (LSA_UNICODE_STRING)Marshal.PtrToStructure(new IntPtr(ptr), typeof(LSA_UNICODE_STRING)); string userRightStr = Marshal.PtrToStringAuto(userRight.Buffer); rights.Add(userRightStr); ptr += Marshal.SizeOf(userRight); } LsaClose(policyHandle); } FreeSid(sid); } if (winErrorCode > 0) { throw new ApplicationException(string.Format("Error occured in LSA, error code {0}, detail: {1}", winErrorCode, errorMessage)); } return rights; } // Adds a privilege to an account public void SetRight(string accountName, string privilegeName) { long winErrorCode = 0; string errorMessage = string.Empty; IntPtr sid = IntPtr.Zero; int sidSize = 0; StringBuilder domainName = new StringBuilder(); int nameSize = 0; int accountType = 0; LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType); domainName = new StringBuilder(nameSize); sid = Marshal.AllocHGlobal(sidSize); if (!LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType)) { winErrorCode = GetLastError(); errorMessage = string.Format("LookupAccountName failed: {0}", winErrorCode); } else { LSA_UNICODE_STRING systemName = new LSA_UNICODE_STRING(); IntPtr policyHandle = IntPtr.Zero; LSA_OBJECT_ATTRIBUTES objectAttributes = CreateLSAObject(); uint resultPolicy = LsaOpenPolicy(ref systemName, ref objectAttributes, Access, out policyHandle); winErrorCode = LsaNtStatusToWinError(Convert.ToInt32(resultPolicy)); if (winErrorCode != 0) { errorMessage = string.Format("OpenPolicy failed: {0} ", winErrorCode); } else { LSA_UNICODE_STRING[] userRights = new LSA_UNICODE_STRING[1]; userRights[0] = new LSA_UNICODE_STRING(); userRights[0].Buffer = Marshal.StringToHGlobalUni(privilegeName); userRights[0].Length = (UInt16)(privilegeName.Length * UnicodeEncoding.CharSize); userRights[0].MaximumLength = (UInt16)((privilegeName.Length + 1) * UnicodeEncoding.CharSize); int res = LsaAddAccountRights(policyHandle, sid, userRights, 1); winErrorCode = LsaNtStatusToWinError(Convert.ToInt32(res)); if (winErrorCode != 0) { errorMessage = string.Format("LsaAddAccountRights failed: {0}", winErrorCode); } LsaClose(policyHandle); } FreeSid(sid); } if (winErrorCode > 0) { throw new ApplicationException(string.Format("Failed to add right {0} to {1}. Error detail:{2}", accountName, privilegeName, errorMessage)); } } public void SetRights(string accountName, IList<string> rights) { rights.ToList().ForEach(right => SetRight(accountName, right)); } private static LSA_OBJECT_ATTRIBUTES CreateLSAObject() { LSA_OBJECT_ATTRIBUTES newInstance = new LSA_OBJECT_ATTRIBUTES(); newInstance.Length = 0; newInstance.RootDirectory = IntPtr.Zero; newInstance.Attributes = 0; newInstance.SecurityDescriptor = IntPtr.Zero; newInstance.SecurityQualityOfService = IntPtr.Zero; return newInstance; } } // Local security rights managed by the Local Security Authority public class LocalSecurityAuthorityRights { // Log on as a service right public const string LogonAsService = "SeServiceLogonRight"; // Log on as a batch job right public const string LogonAsBatchJob = "SeBatchLogonRight"; // Interactive log on right public const string InteractiveLogon = "SeInteractiveLogonRight"; // Network log on right public const string NetworkLogon = "SeNetworkLogonRight"; // Generate security audit logs right public const string GenerateSecurityAudits = "SeAuditPrivilege"; } }