Click here to Skip to main content
13,296,377 members (51,787 online)
Click here to Skip to main content
Add your own
alternative version


63 bookmarked
Posted 27 Aug 2003

LSA Functions - Privileges and Impersonation

, 27 Aug 2003
Rate this:
Please Sign up or sign in to vote.
Managing privileges and impersonating users


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.

[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:

[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:

[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:

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.

//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.

//initialize an empty unicode-string

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

//these attributes are not used, but LsaOpenPolicy 
//wants them to exists

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

And finally we are ready to add privileges.

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

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:

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.

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.

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

Of course we have to free the handles at last.

if (existingTokenHandle != IntPtr.Zero)
if (duplicateTokenHandle != IntPtr.Zero)

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


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.


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


About the Author

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

You may also be interested in...

Comments and Discussions

QuestionSmall memory leak Pin
MrMikeJJ7-Sep-16 3:30
memberMrMikeJJ7-Sep-16 3:30 
QuestionImmediate effect Pin
FredWah30-Dec-15 10:23
memberFredWah30-Dec-15 10:23 
QuestionProblems when running this code on Microsoft Server 2012 Pin
Uittenhove18-May-15 23:10
memberUittenhove18-May-15 23:10 
AnswerRe: Problems when running this code on Microsoft Server 2012 Pin
Uittenhove21-May-15 3:18
memberUittenhove21-May-15 3:18 
QuestionHow to use it in windows 8.1 Pin
er.prakash.bhatta28-Oct-14 23:14
memberer.prakash.bhatta28-Oct-14 23:14 
QuestionMassively Helpful Pin
golyaht2-Aug-13 11:56
membergolyaht2-Aug-13 11:56 
QuestionChceck "SeServiceLogonRight already" exist or not for user? Pin
ankyshah26-Jan-11 21:06
memberankyshah26-Jan-11 21:06 
GeneralNice article, even if there are some errors. Pin
iq-man29-Nov-09 23:09
memberiq-man29-Nov-09 23:09 
GeneralRe: Nice article, even if there are some errors. Pin
alexdresko23-Dec-09 9:37
memberalexdresko23-Dec-09 9:37 
GeneralRe: Nice article, even if there are some errors. Pin
iq-man26-Dec-09 3:11
memberiq-man26-Dec-09 3:11 
GeneralRe: Nice article, even if there are some errors. Pin
alexdresko26-Dec-09 8:21
memberalexdresko26-Dec-09 8:21 
GeneralA bit messy... Pin
Jecho Jekov12-Jun-09 10:35
memberJecho Jekov12-Jun-09 10:35 
GeneralRe: A bit messy... Pin
Mark Richards27-Mar-12 6:24
memberMark Richards27-Mar-12 6:24 
QuestionError adding "Logon As Service" right to User Account Pin
sullivrp2-Jun-09 8:00
membersullivrp2-Jun-09 8:00 
AnswerRe: Error adding "Logon As Service" right to User Account Pin
sullivrp3-Jun-09 9:48
membersullivrp3-Jun-09 9:48 
GeneralRe: Error adding "Logon As Service" right to User Account Pin
Corinna John3-Jun-09 10:14
memberCorinna John3-Jun-09 10:14 
GeneralRe: Error adding "Logon As Service" right to User Account Pin
sullivrp3-Jun-09 11:22
membersullivrp3-Jun-09 11:22 
GeneralRe: Error adding "Logon As Service" right to User Account Pin
Corinna John3-Jun-09 11:51
memberCorinna John3-Jun-09 11:51 
GeneralRe: Error adding "Logon As Service" right to User Account Pin
sullivrp4-Jun-09 6:39
membersullivrp4-Jun-09 6:39 
AnswerRe: Error adding "Logon As Service" right to User Account Pin
ankyshah26-Jan-11 21:08
memberankyshah26-Jan-11 21:08 
Questionhow give user'privilege to a programm ? Pin
vincent3120-Oct-06 7:45
membervincent3120-Oct-06 7:45 
AnswerRe: how give user'privilege to a programm ? Pin
vincent3120-Oct-06 8:57
membervincent3120-Oct-06 8:57 
GeneralLsaNtStatusToWinError work incorect. Pin
Seregil15-Jun-06 2:02
memberSeregil15-Jun-06 2:02 
GeneralChanging Domain Group Policy Pin
Scott S.22-May-06 6:29
memberScott S.22-May-06 6:29 
QuestionImpersonation??? Pin
tee_jay23-Mar-06 8:46
membertee_jay23-Mar-06 8:46 
AnswerRe: Impersonation??? Pin
Scott S.22-May-06 6:14
memberScott S.22-May-06 6:14 

You can't do it with just a SID otherwise every virus out there would impersonate Administrator using its well known SID!
If you also had the password, you could lookup the account name matching the SID to do the logon.

The only other way I can think of off hand is complicated...
* Must be using Kerberos for authentication
* Your process's identity (logged on user?) has to have delegation privilege
* The user you want to impersonate has to be logged on
* A process they are running must pass a kerberos authentication token to your process that includes the delegation information
* Your process must receive the kerberos info set it into the thread
* The thread must then enable impersonation
Good luck if you go this route because as I said above, it is complicated ... I attempted it in the past in C# over remoting and had it working "most of the time" ... sometimes it just failed and I was never able to determine why.Sigh | :sigh:

The question is: "When is Microsoft going to add optional security to the .NET remoting framework classes to automate authentication and impersonation?"

Scott S
GeneralLsaOpenPolicy Error...again Pin
mr24shoe20-Mar-06 13:22
membermr24shoe20-Mar-06 13:22 
GeneralRe: LsaOpenPolicy Error...again Pin
Jecho Jekov12-Jun-09 10:37
memberJecho Jekov12-Jun-09 10:37 
GeneralVery good job Pin
segelfix19-Mar-06 11:48
membersegelfix19-Mar-06 11:48 
GeneralImpersonation - Console App - SAMBA Pin
lucasfong6-Jan-05 11:55
memberlucasfong6-Jan-05 11:55 
GeneralLsaOpenPolicy Error Pin
Kermittt15-Sep-04 21:42
memberKermittt15-Sep-04 21:42 
GeneralRe: LsaOpenPolicy Error Pin
gav_jackson5-Jan-05 5:24
membergav_jackson5-Jan-05 5:24 
GeneralRe: LsaOpenPolicy Error Pin
Kermittt5-Jan-05 12:58
memberKermittt5-Jan-05 12:58 
GeneralRe: LsaOpenPolicy Error Pin
gav_jackson5-Jan-05 22:59
membergav_jackson5-Jan-05 22:59 
GeneralRe: LsaOpenPolicy Error Pin
Kermittt6-Jan-05 12:49
memberKermittt6-Jan-05 12:49 
GeneralRe: LsaOpenPolicy Error Pin
Tokus17-Jul-06 9:53
memberTokus17-Jul-06 9:53 
GeneralRe: LsaOpenPolicy Error Pin
neotussanonis24-May-07 14:13
memberneotussanonis24-May-07 14:13 
QuestionUndocumented Lsa* Functions?? Pin
Dan Madden26-Aug-04 7:49
memberDan Madden26-Aug-04 7:49 
AnswerRe: Undocumented Lsa* Functions?? Pin
Corinna John29-Aug-04 2:19
memberCorinna John29-Aug-04 2:19 
Generalquestion Pin
lwcotton91918-Aug-04 0:28
memberlwcotton91918-Aug-04 0:28 
AnswerRe: question Pin
tee_jay23-Mar-06 8:43
membertee_jay23-Mar-06 8:43 
GeneralAppDomain Impersonation Pin
chriskoiak16-Mar-04 1:27
memberchriskoiak16-Mar-04 1:27 
GeneralRe: AppDomain Impersonation Pin
mjesterak25-Jan-06 19:33
membermjesterak25-Jan-06 19:33 
GeneralSID Retrieving Pin
smidz11-Feb-04 6:50
membersmidz11-Feb-04 6:50 
GeneralRe: SID Retrieving Pin
Dan Madden26-Aug-04 7:35
memberDan Madden26-Aug-04 7:35 
GeneralImpersonation Pin
DidactSoft23-Jan-04 22:22
memberDidactSoft23-Jan-04 22:22 
GeneralRe: Impersonation Pin
Corinna John24-Jan-04 2:25
memberCorinna John24-Jan-04 2:25 
GeneralError When Trying to Impersonate Against the Domain Pin
frosty86753094-Sep-03 10:45
memberfrosty86753094-Sep-03 10:45 
GeneralRe: Error When Trying to Impersonate Against the Domain Pin
Corinna John4-Sep-03 11:27
memberCorinna John4-Sep-03 11:27 
GeneralRe: Error When Trying to Impersonate Against the Domain Pin
frosty86753094-Sep-03 12:25
memberfrosty86753094-Sep-03 12:25 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171207.1 | Last Updated 28 Aug 2003
Article Copyright 2003 by Corinna John
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid