Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C#
Article

LSA Functions - Privileges and Impersonation

Rate me:
Please Sign up or sign in to vote.
4.46/5 (31 votes)
27 Aug 2003CPOL2 min read 261.1K   4.3K   64   53
Managing privileges and impersonating users

Introduction

Sometimes you want your application to do things which the user himself may never do. For example, your application has to read a public folder on an exchange server, but the folder is hidden from the active user for good reasons. Now you need LSA functions, to manage privileges and impersonate another user. This article explains how to import the LSA functions, add rights to accounts and impersonate different users.

SIDs, Policies and Rights

Whenever you alter the privileges of an account, you need its Security Identifier (SID). You can find any account using LookupAccountName.

C#
[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 ); 

Before adding  or removing any privileges, we need a policy handle. LsaOpenPolicy opens a handle:

C#
[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 ); 

Using the SID and the policy handle, LsaAddAccountRights can add privileges:

C#
[DllImport("advapi32.dll", SetLastError=true, PreserveSig=true)]
private static extern long LsaAddAccountRights(
    IntPtr PolicyHandle, IntPtr AccountSid, 
    LSA_UNICODE_STRING[] UserRights,
    long CountOfRights ); 

The LSA functions work with Unicode strings, so we have to use the LSA_UNICODE_STRING structure. This structure contains a buffer for the string, an two integers for the length of the buffer and the length of the actual string in the buffer:

C#
[StructLayout(LayoutKind.Sequential)]
private struct LSA_UNICODE_STRING 
{ 
  public UInt16 Length; 
  public UInt16 MaximumLength; 
  public IntPtr Buffer; 
} 

Now it's time to call these functions. First, find the desired account and retrieve the SID.

C#
//pointer an size for the SID
IntPtr sid = IntPtr.Zero;
int sidSize = 0; 

//StringBuilder and size for the domain name
StringBuilder domainName = new StringBuilder();
int nameSize = 0;

//account-type variable for lookup
int accountType = 0; 

//get required buffer size
LookupAccountName(String.Empty, accountName, sid, ref sidSize, 
    domainName, ref nameSize, ref accountType); 

//allocate buffers
domainName = new StringBuilder(nameSize);
sid = Marshal.AllocHGlobal(sidSize);

//lookup the SID for the account
bool result = LookupAccountName(String.Empty, accountName, sid, 
    ref sidSize, domainName, ref nameSize, ref accountType); 

And secondly, open a policy handle.

C#
//initialize an empty unicode-string
LSA_UNICODE_STRING systemName = new LSA_UNICODE_STRING(); 

//initialize a pointer for the policy handle
IntPtr policyHandle = IntPtr.Zero; 

//these attributes are not used, but LsaOpenPolicy 
//wants them to exists
LSA_OBJECT_ATTRIBUTES ObjectAttributes = new LSA_OBJECT_ATTRIBUTES();

//get a policy handle
uint resultPolicy = LsaOpenPolicy(ref systemName, ref ObjectAttributes, 
    access, out policyHandle);

And finally we are ready to add privileges.

C#
//initialize an unicode-string for the privilege name
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 );

//add the privilege to the account 
long res = LsaAddAccountRights(policyHandle, sid, userRights, 1);
winErrorCode = LsaNtStatusToWinError(res); 
if(winErrorCode != 0)
{ 
    Console.WriteLine("LsaAddAccountRights failed: "+ winErrorCode); 
} 
//close all handles 
LsaClose(policyHandle); 
FreeSid(sid); 

More LSA

Now we can manage user's privileges - but how about being another user? LSA includes a set of functions to impersonate any user. This means, performing an invisible logon an switch between our own identity and the new one.

For example, if you're writing a service and you don't get along with network access of the local service authority, you can define a special domain account for your service and impersonate it at runtime. LogonUser is the function to authenticate a user against a domain:

C#
[DllImport("advapi32.dll")]
private static extern bool LogonUser( 
    String lpszUsername, 
    String lpszDomain, 
    String lpszPassword, 
    int dwLogonType, 
    int dwLogonProvider, 
    ref IntPtr phToken );

LogonUser verifies the logon parameters an creates a security token. Whenever a user logs onto a workstation, a security token is created. All applications launched by this user hold a copy of this token. He have to copy our new token using DuplicateToken.

C#
[DllImport("advapi32.dll")]
private static extern bool DuplicateToken( 
    IntPtr ExistingTokenHandle, 
    int ImpersonationLevel, 
    ref IntPtr DuplicateTokenHandle );

Now we got a copy of the security token, we can create a WindowsIdentity and impersonate the user. The .NET framework contains classes for impersonating users, once we got the right token.

C#
using System.Security.Principal;
//...
WindowsIdentity newId = new WindowsIdentity(duplicateTokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();

Of course we have to free the handles at last.

C#
if (existingTokenHandle != IntPtr.Zero)
{ 
    CloseHandle(existingTokenHandle); 
} 
if (duplicateTokenHandle != IntPtr.Zero)
{ 
    CloseHandle(duplicateTokenHandle); 
} 

When we have finished the special tasks, we can switch back to our normal identity

C#
impersonatedUser.Undo(); 

Using the code

In the LogonDemo project there are LsaUtility.cs and LogonUtility.cs. LsaUtility.cs imports the functions necessary for managing privileges and contains the static method

SetRight (String 
accountName, String privilegeName)
. It adds a named privilege to an account. LogonUtility.cs contains everything you need to impersonate a user.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Germany Germany
Corinna lives in Hanover/Germany and works as a C# developer.

Comments and Discussions

 
QuestionUndocumented Lsa* Functions?? Pin
Dan Madden26-Aug-04 6:49
Dan Madden26-Aug-04 6:49 
AnswerRe: Undocumented Lsa* Functions?? Pin
Corinna John29-Aug-04 1:19
Corinna John29-Aug-04 1:19 
Generalquestion Pin
lwcotton91917-Aug-04 23:28
lwcotton91917-Aug-04 23:28 
AnswerRe: question Pin
tee_jay23-Mar-06 7:43
tee_jay23-Mar-06 7:43 
GeneralAppDomain Impersonation Pin
chriskoiak16-Mar-04 0:27
chriskoiak16-Mar-04 0:27 
GeneralRe: AppDomain Impersonation Pin
Matt Esterak25-Jan-06 18:33
Matt Esterak25-Jan-06 18:33 
GeneralSID Retrieving Pin
zdenek.smid11-Feb-04 5:50
zdenek.smid11-Feb-04 5:50 
GeneralRe: SID Retrieving Pin
Dan Madden26-Aug-04 6:35
Dan Madden26-Aug-04 6:35 
If you haven't got it yet:

To Get the SID....

<br />
Example:   <br />
<br />
GetAccountSid(NULL,"UserName",&sid);<br />
<br />
<br />
//////////////////////////////////////////////////////////////////////<br />
BOOL GetAccountSid(LPTSTR SystemName, LPTSTR AccountName, PSID *Sid)<br />
{<br />
	LPTSTR ReferencedDomain=NULL;<br />
	DWORD cbSid=128;    // initial allocation attempt<br />
	DWORD cchReferencedDomain=16; // initial allocation size<br />
	SID_NAME_USE peUse;<br />
	BOOL bSuccess=FALSE; // assume this function will fail<br />
<br />
	__try {<br />
<br />
		//<br />
		// initial memory allocations<br />
		//<br />
		*Sid = (PSID)HeapAlloc(GetProcessHeap(), 0, cbSid);<br />
<br />
		if(*Sid == NULL) __leave;<br />
<br />
		ReferencedDomain = (LPTSTR)HeapAlloc(GetProcessHeap(),0,cchReferencedDomain * sizeof(TCHAR));<br />
		if(ReferencedDomain == NULL) __leave;<br />
<br />
		//<br />
		// Obtain the SID of the specified account on the specified system.<br />
		//<br />
		while(!LookupAccountName(<br />
						SystemName,         // machine to lookup account on<br />
						AccountName,        // account to lookup<br />
						*Sid,               // SID of interest<br />
						&cbSid,             // size of SID<br />
						ReferencedDomain,   // domain account was found on<br />
						&cchReferencedDomain,<br />
						&peUse<br />
						)) {<br />
			if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {<br />
				//<br />
				// reallocate memory<br />
				//<br />
				*Sid = (PSID)HeapReAlloc(GetProcessHeap(),<br />
										 0,<br />
										 *Sid,<br />
										 cbSid);<br />
<br />
				if(*Sid == NULL) __leave;<br />
<br />
				ReferencedDomain = (LPTSTR)HeapReAlloc( GetProcessHeap(),<br />
														0,<br />
														ReferencedDomain,<br />
														cchReferencedDomain * sizeof(TCHAR));<br />
<br />
				if(ReferencedDomain == NULL) __leave;<br />
			}<br />
			else __leave;<br />
		}<br />
<br />
		//<br />
		// Indicate success.<br />
		//<br />
		bSuccess=TRUE;<br />
<br />
	} // try<br />
	__finally {<br />
<br />
		//<br />
		// Cleanup and indicate failure, if appropriate.<br />
		//<br />
<br />
		HeapFree(GetProcessHeap(), 0, ReferencedDomain);<br />
<br />
		if(!bSuccess) {<br />
			if(*Sid != NULL) {<br />
				HeapFree(GetProcessHeap(), 0, *Sid);<br />
				*Sid = NULL;<br />
			}<br />
		}<br />
<br />
    } // finally<br />
<br />
    return bSuccess;<br />
}<br />
<br />


Now to Make it Text:

Example:

<br />
....<br />
	LPSTR sidText = NULL;<br />
	DWORD cbSid = 128;<br />
<br />
	sidText = (LPSTR) LocalAlloc(LPTR, cbSid);<br />
	if (sidText)<br />
	{<br />
		if(GetTextualSid(psid, sidText, &cbSid)) {<br />
			m_edtSID.SetWindowText(sidText);<br />
		} else {<br />
			m_edtSID.SetWindowText("");<br />
		}<br />
		LocalFree(sidText);<br />
	}<br />
....<br />
<br />
////////////////////////////////////////////////////////////////////<br />
BOOL GetTextualSid(PSID pSid, PTSTR TextualSid, PDWORD pdwBufferLen) <br />
{<br />
	BOOL fSuccess = FALSE;<br />
<br />
    try {{<br />
		// Test if Sid passed in is valid<br />
        if (!IsValidSid(pSid))<br />
			goto leave;<br />
<br />
        // Obtain Sid identifier authority<br />
        PSID_IDENTIFIER_AUTHORITY psia = GetSidIdentifierAuthority(pSid);<br />
<br />
        // Obtain sid subauthority count<br />
        DWORD dwSubAuthorities = *GetSidSubAuthorityCount(pSid);<br />
<br />
        // Compute buffer length<br />
        // S-SID_REVISION-+identifierauthority-+subauthorities-+NULL<br />
        DWORD dwSidSize = (15 + 12 + (12 * dwSubAuthorities) + 1)<br />
            * sizeof(TCHAR);<br />
<br />
        // Check provided buffer length.<br />
        // If not large enough, indicate proper size and SetLastError<br />
        if (*pdwBufferLen < dwSidSize) <br />
		{<br />
			*pdwBufferLen = dwSidSize;<br />
            SetLastError(ERROR_INSUFFICIENT_BUFFER);<br />
            goto leave;<br />
		}<br />
<br />
        // prepare S-SID_REVISION-<br />
        dwSidSize = wsprintf(TextualSid, TEXT("S-%lu-"), SID_REVISION);<br />
<br />
        // Prepare Sid identifier authority<br />
        if ((psia->Value[0] != 0) || (psia->Value[1] != 0)) <br />
		{<br />
			dwSidSize += wsprintf(TextualSid + lstrlen(TextualSid),<br />
               TEXT("0x%02hx%02hx%02hx%02hx%02hx%02hx"),<br />
               (USHORT) psia->Value[0], (USHORT) psia->Value[1],<br />
               (USHORT) psia->Value[2], (USHORT) psia->Value[3],<br />
               (USHORT) psia->Value[4], (USHORT) psia->Value[5]);<br />
		}<br />
		else<br />
		{<br />
            dwSidSize += wsprintf(TextualSid + lstrlen(TextualSid),<br />
               TEXT("%lu"), (ULONG) (psia->Value[5])<br />
               + (ULONG) (psia->Value[4] << 8)<br />
               + (ULONG) (psia->Value[3] << 16)<br />
               + (ULONG) (psia->Value[2] << 24));<br />
		}<br />
<br />
        // Loop through sid subauthorities<br />
        DWORD dwCounter;<br />
        for (dwCounter = 0; dwCounter < dwSubAuthorities; dwCounter++) <br />
		{<br />
			dwSidSize += wsprintf(TextualSid + dwSidSize, TEXT("-%lu"),<br />
               *GetSidSubAuthority(pSid, dwCounter));<br />
		}<br />
<br />
        fSuccess = TRUE;<br />
    } leave:;<br />
    } catch(...) {}<br />
<br />
    return(fSuccess);<br />
}<br />



Regards,

Dan
GeneralImpersonation Pin
DidactSoft23-Jan-04 21:22
DidactSoft23-Jan-04 21:22 
GeneralRe: Impersonation Pin
Corinna John24-Jan-04 1:25
Corinna John24-Jan-04 1:25 
GeneralError When Trying to Impersonate Against the Domain Pin
frosty86753094-Sep-03 9:45
frosty86753094-Sep-03 9:45 
GeneralRe: Error When Trying to Impersonate Against the Domain Pin
Corinna John4-Sep-03 10:27
Corinna John4-Sep-03 10:27 
GeneralRe: Error When Trying to Impersonate Against the Domain Pin
frosty86753094-Sep-03 11:25
frosty86753094-Sep-03 11:25 
GeneralRe: Error When Trying to Impersonate Against the Domain Pin
Corinna John4-Sep-03 19:16
Corinna John4-Sep-03 19:16 
GeneralRe: Error When Trying to Impersonate Against the Domain Pin
frosty86753095-Sep-03 4:53
frosty86753095-Sep-03 4:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.