Author: Chris Baldwin
How can I impersonate another NT User account at runtime so my process is
recognised as the impersonated user.
Answer:
There are many different reason you might need to run an application/server as a
different user, so you can perform tasks on behalf of that user account, or obtain
privileges of that user so as to beable to perform specified tasks.
i.e File/Network access, registry etc..
Logging on as a different user from an application, and impersonating that user is
not a differcult task by use of API calls provide, but many people miss the
security side to this and fail to realize the requirement for NT security
privileges, and how to assign those security rights to them selves to allow
them to do a Logon.
The call LogonUser requires the privilege of SE_TCB_NAME which requires you to have
the right "Act as part of the Operating System" assigned to your user account
before you can Logon as a different user.
Through NT this is done through local user manager, and on 2000 is done through
computer local policy control etc..
Ask your Technical administrator for details on assigning Security Rights to
users.!
Once you have assigned your self the right of "Act as part of the Operating System"
you automatically have rights to call the LogonUser api call.
Note: For those who know about NT privileges and setting the enable flag to
privileges, you don't need to set the privilege all that is required is that yhou
have the privilege available to you.
So here is how it is done.
1 var
2 hToken: Cardinal;
3
4 function PerformLogon(const User, Domain, Password: string): Cardinal;
5 begin
6 if not LogonUser(pChar(User), pChar(Domain), pChar(Password),
7 LOGON32_LOGON_NETWORK,
8 LOGON32_PROVIDER_DEFAULT,
9 Result) then
10 RaiseLastWin32Error;
11 end;
12
13 begin
14 hToken := PerformLogon('Chris', 'DelphiDomain', 'MyPassword');
15 try
16 ImpersonateLoggedOnUser(hToken);
17 try
18 (* Perform tasks as User. *)
19 finally
20 RevertToSelf;
21 end;
22 finally
23 CloseHandle(hToken);
24 end;
25 end;
Well that is pretty much it, however.. note that LogonUser is only passing you an
impersonation token, and not a primary token in this instance. You can use the api
calls DuplicateTokenEx, or CreateProcessAsUser which can help with creating Primary
Tokens...
Also note that, when your impersonation is required to pass over to the
authentication of COM for example, this method will not work on it's own.
I have published an article which details authentication and impersonation for COM
authentication. Refer to :
Specifing authentication details & Impersonating a user for use on an Interface(Proxy)call (Client Side)
|