2006. október 29., vasárnap

Logon and Impersonate another NT User Account (NT/2000 Only)


Problem/Question/Abstract:

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.

var
  hToken: Cardinal;

function PerformLogon(const User, Domain, Password: string): Cardinal;
begin
  if not LogonUser(pChar(User), pChar(Domain), pChar(Password),
    LOGON32_LOGON_NETWORK,
    LOGON32_PROVIDER_DEFAULT,
    Result) then
    RaiseLastWin32Error;
end;

begin
  hToken := PerformLogon('Chris', 'DelphiDomain', 'MyPassword');
  try
    ImpersonateLoggedOnUser(hToken);
    try
      (* Perform tasks as User. *)
    finally
      RevertToSelf;
    end;
  finally
    CloseHandle(hToken);
  end;
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)

Nincsenek megjegyzések:

Megjegyzés küldése