A .NET Developer's Guide to Windows Security: Understanding Impersonation
Impersonation is one of the most useful mechanisms in Windows security. It's also fragile and easy to misuse. Careful use of impersonation can lead to a secure, easy-to-administer application. Misuse can open gaping security holes.
After an application authenticates a user, the application can take on that user's identity through impersonation. Impersonation happens on a thread-by-thread basis to allow for concurrency, which is important for multithreaded servers as each thread might be servicing a different client. In Figure 31.1, the server process is configured to run as Bob. It contains five threads, two of which are impersonating in order to do work on behalf of authenticated clients.
Figure 31.1 Impersonation basics
In this scenario, if one of the three normal threads tries to open a file (or any other secure kernel object), the operating system makes its access-checking and auditing decisions by looking at the process token. If Bob has the requisite access, the call will succeed and any audits will show that Bob opened the file. On the other hand, if the thread impersonating Alice tries to open the same file, the operating system makes its access-check decision based on Alice's token, not Bob's, so Alice, not Bob needs to be granted access to the file in this case. As for auditing, the operating system cares about both identities and will record that Bob was impersonating Alice when the file was opened. Of course, auditing must be enabled for any audits to be generated at all (Item 10)!
It may seem surprising that Bob can impersonate his client and actually become more privileged than before. This (and the reverse) is true. Bob might have very little privilege and have access to very few resources on his own, but think about the benefits of this model. If the server process is somehow hijacked by a bad guy, perhaps via a buffer overflow (Item 1), the bad guy won't immediately obtain access to lots of valuable resources. Instead, he'll immediately be able to use only the few piddly resources that Bob can access. Either he'll have to exploit another hole in the system to elevate privileges or he'll have to wait around until a client connects and use the client's credentials to access those resources (via impersonation!). And unless the client is highly privileged, the bad guy won't immediately have access to all the resources but rather only to the ones that that client can access. This can slow down an attack, giving your detection countermeasures (Item 2) time to kick in and allowing you to react and cut off the attack.
Imagine the opposite scenario, where the server runs as SYSTEM and impersonates incoming clients. If the server process is hijacked, it's pretty much over as far as any local resources go. And you should be aware that impersonating a low-privileged account, even the null session (Item 35), won't stop an attacker from simply removing the impersonation token by calling the Win32 function RevertToSelf before doing his evil deeds. This call requires no special privileges and no arguments. It simply removes the impersonation token from the thread, reverting the thread back to the process's identity.
You see, in the first scenario there's a trust boundary between the server process and the resources it's accessing. The resources won't accept Bob's credentials but rather want proof that an authorized client has connected. There's also a trust boundary between the server process and the operating system. There's none in the second scenario! These trust boundaries become even more important when impersonation turns into delegation (Item 62).
None of this is perfect. Even when Bob is untrusted, he can still do bad things. He can collect client tokens (Item 16), which never time out and so effectively elevate the overall privilege level of his process over time. When Alice connects and asks to read resource A, Bob can instead choose to misuse her credentials and write to resource B. But don't let that dissuade you from running your servers with least privilege (Item 4). Security is a balancing act, and least privilege usually gives the defender an advantage.
Pitfalls to Watch For
As you've seen, impersonation can be a very useful tool in the hands of an architect. Implemention pitfalls abound, however, so read on to make sure you don't fall into one. First of all, impersonation puts your thread into a somewhat wacky state. You've got two identities, controlled by your process token and your thread token. In some cases, this can cause surprising behavior. For example, almost all my students are surprised when I tell them how process creation works. Say the thread impersonating Alice in Figure 31.1 creates a new process, perhaps by calling Process.Start. Alice will need to have execute permissions on the EXE being launched, but the new process will run with a copy of Bob's token. That's righteven when impersonating, new processes are naturally launched with a copy of their parent's process token. A special function, CreateProcessAsUser, allows you to specify a different token, but it's very tricky to use (Brown 2000a), and you can often accomplish the same thing more easily with the Secondary Logon Service (Item 30).
Here's another gotcha. When making an outgoing DCOM call, unless a rather esoteric feature called "cloaking" is enabled, COM ignores the impersonation token and uses your process's credentials to make the call. Thus a COM server sees Bob making the call instead of Alice in our example. Now in many important cases, cloaking is enabled by default, such as in any COM+ server process (DLLHOST.EXE) or in an IIS worker process (W3WP.EXE). But if you write a service, for example, and you don't call CoInitializeSecurity yourself (Item 52), cloaking won't be on by default.
Here's a nasty one. Imagine you're running a trusted server such as in our second example, which ran as SYSTEM. Say you're impersonating some low-privileged account and you make some call that happens to either create a new thread or switch threads to implement the call, perhaps via an asynchronous delegate (BeginInvoke). As of this writing, the operating system makes no effort to propagate the impersonation token to the secondary thread. Let me give you a classic example that lots of people have run into in ASP Web applications and that's still present today in ASP.NET. A trusted ASP.NET application is configured to run as SYSTEM. It's also configured for impersonation so that it impersonates each client as it performs its work. If part of that work is to call to an in-process COM component that's thread unaware (like all those VB6 components out there), there will be a hidden thread switch during the call and the component will run on a COM worker thread instead of on the caller's thread.  That VB6 component is now running as SYSTEM, and that's probably not what you intended!
Here's a rather esoteric gotcha in ASP.NET. If you write an asynchronous handler by implementing IHttpAsyncHandler, realize that if you want to handle the request on a worker thread, you need to propagate any impersonation token manually. This is the case if, for example, you set up your web.config file to enable impersonation for your application.
<configuration> <system.web> <identity impersonate='true'/> </system.web> </configuration>
Manually propagating the token won't be that hard. Just call WindowsIdentity.GetCurrent() to get a WindowsIdentity that wraps the impersonation token (Item 24) in your BeginProcessRequest code, and communicate it to your worker thread. Before your worker thread executes the request, it should call WindowsIdentity.Impersonate and then Undo the impersonation after the work is finished. Assume that each request comes from a different user. Be absolutely certain that each request executes using the correct impersonation token. Don't get those tokens crossed!
On a final note, be careful to close kernel handles aggressively when impersonating. You see, handles to objects are like preauthorized sessions. Once a handle is open to a file, registry key, mutex, and the like, the system performs no further access checks when it is used. The handle itself is tracked by the operating system based on which permissions were granted when it was opened, so the system can ensure that a handle opened for reading isn't subsequently used for writing. But if our thread in Figure 31.1 impersonating Alice decides to open a file that only Alice has access to, nothing but careful programming prevents any other threads in that process from using that handle as well. If the handle isn't closed when Alice disconnects, it might "leak" and be used by the server accidentally when the next user connects. In a nutshell, handles are insensitive to security context changes. Start impersonating, stop impersonating, impersonate someone elseno matter: The handles you've already opened don't care (even with auditing enabled, the only time an event is normally recorded is when a handle is first opened). Oh, and you're not exempt if you're using the .NET Framework library to open files and other objects. Each FileStream holds a file handle under the covers, so call Dispose on those FileStream objects aggressively!