Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Impersonation from C#

How can a C# program running as LocalSystem impersonate the login identity of another user temporarily? Roughly speaking I have a Windows Service that I'd like to run as LocalSystem but at times impersonate user XYZ (when connecting to a db using windows integrated security).

Most important of all: Is there a way to do this without knowing the other user's password?

Note: if a password is mandatory is there a recommended strategy for storing a password securely (c# and/or vbscript).

like image 289
user53794 Avatar asked Feb 18 '09 03:02

user53794


People also ask

What is impersonation C#?

Impersonation is the process of executing code in the context of another user identity. By default, all ASP.NET code is executed using a fixed machine-specific account. To execute code using another identity we can use the built-in impersonation capabilities of ASP.NET.

How do I know if impersonation is working C#?

Just examine the ImpersonationLevel property of the WindowsIdentity class. Identification - The server process can obtain information about the client... Impersonation - The server process can impersonate the client's security context on its local system.

How do I enable impersonation in Web config?

In the application's Web. config file, set the impersonate attribute in the identity element to true. Set the NTFS access control list (ACL) for the ManagerInformation directory to allow access to only those identities that are in the Windows Manager group and any required system accounts.


2 Answers

It's possible, although it requires you to do a lot of code. See NtCreateToken and CreateToken. You need SeCreateTokenPrivilege, although that won't be a problem since you're running under NT AUTHORITY\SYSTEM. You can then use the created token to impersonate inside a thread.

like image 199
wj32 Avatar answered Sep 26 '22 02:09

wj32


Short answer: you can't without the user password or the user calling your service through COM.

To impersonate another user in your process, you have to call ImpersonateLoggedOnUser. ImpersonateLoggedOnUser requires a token handle. There are several ways you can obtain token handle:

  • by logging on as the user with LogonUser. This however requires you to know the user password.
  • by duplicating an existing token with CreateRestrictedToken, DuplicateToken, or DuplicateTokenEx.
  • by opening the token from another process or thread, that already is loggen on as the user, with OpenProcessToken or OpenThreadToken
like image 22
Franci Penov Avatar answered Sep 22 '22 02:09

Franci Penov