Home > Articles > Programming > Windows Programming

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. This sample chapter will help you to use impersonation properly and effectively.
This chapter is from the book

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.

31fig01.gifFigure 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 right—even 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. [1] 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 else—no 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!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020