Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#

Requesting Admin Approval at Application Start

Rate me:
Please Sign up or sign in to vote.
4.09/5 (9 votes)
18 Mar 2010CPL7 min read 86.8K   15   5
Learn how to request UAC elevation at application start

Introduction

User Access Control (UAC) is a feature of Windows that can help prevent unauthorized changes to your computer. UAC does this by asking you for permission or an administrator password before performing actions that could potentially affect your computer’s operation or that change settings that affect other users.

With UAC, Administrator users, by default, don't have administrative privileges. Every Windows process has two security tokens associated with it, one with normal user privileges and one with admin privileges. With applications that require administrative privileges, the user can change the application to run with Administrator rights. And that process is called Elevation.

Therefore, when a normal user logs on to the system, he is assigned the standard user access security token that does not allow him to access administrator resources. On the other hand, when an administrator logs on to the system, Windows creates two security tokens for him: a standard user access token and an administrator access token. And he is assigned the latter. When he tries to access a resource that requires administrator privileges, he is asked for elevation. Unless he approved the elevation request, he cannot access that resource. It is worth mentioning that standard users cannot access protected resources. However, they are requested for the elevation, by entering an administrator username and password. Therefore, the administrator accesses the protected resource on behalf of the standard user.

Now, there is a question. Why do I need administrator privileges? Means, what are the resources that are protected? The answer is very simple. Most operations that may affect the system or other users on the machine are access protected. For example, writing a file on the system drive requires admin approval, reading from the registry requires admin approval, and changing file association requires admin approval.

After all, in this lesson, we will learn how to request admin approval at the application start to allow the application to access protected administrator resources.

Requesting Admin Approval via a Manifest

To request the admin approval, you may need to embed a manifest with specific form to the application.

An application manifest is an XML file similar to the application configuration file but it has another construction.

To embed a manifest to the application, you will need to add it to the project and ask Visual Studio to embed it.

The Manifest Construction

The following is the manifest construction:

  • Download this file here.
XML
<?xml version="1.0? encoding="utf-8??><asmv1:assembly manifestVersion="1.0?
                xmlns="urn:schemas-microsoft-com:asm.v1?
                xmlns:asmv1="urn:schemas-microsoft-com:asm.v1?
                xmlns:asmv2="urn:schemas-microsoft-com:asm.v2?
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <assemblyIdentity version="1.0.0.0? name="MyApplication.app"/>
    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2?>
        <security>
            <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3?>
                <requestedExecutionLevel
                    level="requireAdministrator" uiAccess="false" />
            </requestedPrivileges>
        </security>
    </trustInfo>
</asmv1:assembly>

You can also add this manifest file via the Add New Item dialog. However, VB.NET adds it automatically. But be sure to edit it.

This manifest should be named the way you name the configuration file. That means that its name should be app.manifest, so Visual Studio can treat it the right way.

This manifest is nothing more than a simple XML file with a specific construction. You cannot change any element name or a namespace. However, you can set the application required privileges through the attributes level and uiAccess of the requestedExecutionLevel element.

The level attribute specifies the security level that we need to grant the application. It can be one of three values:

  • requireAdministrator:

    Means that the application requires administrator privileges (elevation, in other words.) If this is an administrator, he will be asked for approval. If this is a standard user, he will be asked to provide an administrator’s username and password. Therefore, the administrator executes the application of behalf of the standard user.

  • highestAvailable:

    The application gets the privileges the user has but only after getting the consent from the user. This means that if the user is a standard user, the application gets standard user privileges. On the other hand, if the user is an administrator, the application gets the admin privileges but after the request for elevation.

  • asInvoker:

    The application is running with the security token of the user. This means that if the user is a standard user or an administrator, the application gets the standard user privileges without elevation, and does not request it.

While VB.NET automatically adds the manifest file, it sets requestedExecutionLevel to asInvoker.

The uiAccess option comes in handy if your application requires input to a higher-privilege-level window on the desktop. For example, if your application is an onscreen keyboard. Set uiAccess to true to allow that type of input, or false otherwise.

Actually, you will not be granted the UIAccess privilege unless your application is installed in a secure location like the Program Files directory. If you need to allow all applications located in any place to be granted the UIAccess privilege, you will need to change system policy in the Local Security Policy MMC snap-in. Learn more here.

Automatically Creating the Manifest

To embed the manifest to your application, follow these steps:

  1. Add the manifest file (app.manifest) to the project.
  2. Open the Project Properties dialog.
  3. Switch to the Application tab.
  4. In the Resources section and in the Manifest field, you can choose to embed a default manifest to the application that has the asInvoker level set, to create the application without a manifest and that has the same effect as the previous option, or to choose from a list of manifest files added to the project.

Figure 1 shows how to embed the manifest file.

Figure 1. Embedding a Manifest
Figure 1. Embedding a Manifest

Trying the Example

Now, we are going to write a simple example that illustrates how to request admin approval at the application and how this affects the application progress.

For the example to work well, it is better not to start Visual Studio .NET with admin privileges because if you ran the application from the Visual Studio environment, it will be granted its permissions automatically. However, to see the results, run the application from its file.

Now, start a new project and add the following code to the Main() function:

C#
static void Main()
{
    // Change the drive C to
    // the system drive
    System.IO.File.WriteAllText(
        "C:\\MyFile.txt",
        "Hello, World");
    Console.WriteLine("Completed");
    Console.ReadKey(true);
}

The last code tries to write a file to the system drive which is access protected and requires admin approval to allow the writing.

Now, try to run the application. Unfortunately, because you are not granted the administrator access token, the application will fail and you will be faced with System.UnauthorizedAccessException.

Again, if you started Visual Studio .NET with admin privileges, you will not see how the UAC affects the whole application. In that case, you will need to run the application from its file.

Now, add the manifest to the application and embed it and try to run the application again.

Cheers, succeeded. Now, you are faced with the admin approval message. The following figures show the two types of admin approval messages. Figure 2 shows the prompt for consent message for administrator users, while figure 3 shows the prompt for credentials message for standard users.

Figure 2. Prompt for Consent Message
Figure 2. Prompt for Consent Message
Figure 3. Prompt for Credentials Message
Figure 3. Prompt for Credentials Message

Requesting Admin Approval via the Registry

While you can easily request admin approval via a manifest file during the development process, it will not be the case if the application is already deployed.

Actually, you can request an application to start with admin privileges by right-clicking the application file and choosing “Run as Administrator” item. However, you will need to do this every time you try to run the application.

Another way is to change the application to request admin approval every time you execute it. This is done through the compatibility options in the Properties dialog of the application file. See figure 4.

Figure 4. Compatibility Options
Figure 4. Compatibility Options

Setting this option adds the compatibility flag RUNASADMIN to the registry at SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers that resides in HKCU if you change current user settings or HKLM if you choose to change the settings for all users. Figure 5 shows our application item in the registry.

Figure 5. Compatibility Flags in Registry
Figure 5. Compatibility Flags in Registry

Therefore, you can register an application to run as administrator if you added the compatibility flag RUNASADMIN in the right place.

Actually, you can replace the manifest approach with this way. You make the application installer add this compatibility flag in the installation process which -by default- runs in admin privileges mode.

The Last Word

It is worth mentioning that this does not apply to Windows Vista only, it applies to Windows 7 -and maybe later versions- also. Working with UAC is very exhausting. However, you should relax! Windows 7 fixes major UAC problems. Now, you are not required to grant the permission for such simple operations like changing system date and time.

It is worth mentioning that it is better not to request admin approval for the whole application. It is recommended that you request admin approval for the specific operations that require it only. And this can be done through the Windows Vista SDK.

In addition, you can read more about UAC and how it affects your application flow in these articles:

Good day!

Posted in Windows Security Tagged: .NET, CodeProject, CSharp, Security, UAC, Windows, Windows Vista

License

This article, along with any associated source code and files, is licensed under The Common Public License Version 1.0 (CPL)


Written By
Technical Lead
Egypt Egypt
Mohammad Elsheimy is a developer, trainer, and technical writer currently hired by one of the leading fintech companies in Middle East, as a technical lead.

Mohammad is a MCP, MCTS, MCPD, MCSA, MCSE, and MCT expertized in Microsoft technologies, data management, analytics, Azure and DevOps solutions. He is also a Project Management Professional (PMP) and a Quranic Readings college (Al-Azhar) graduate specialized in Quranic readings, Islamic legislation, and the Arabic language.

Mohammad was born in Egypt. He loves his machine and his code more than anything else!

Currently, Mohammad runs two blogs: "Just Like [a] Magic" (http://JustLikeAMagic.com) and "مع الدوت نت" (http://WithdDotNet.net), both dedicated for programming and Microsoft technologies.

You can reach Mohammad at elsheimy[at]live[dot]com

Comments and Discussions

 
GeneralMy vote of 2 Pin
Wamuti1-Sep-12 4:55
Wamuti1-Sep-12 4:55 
QuestionMy vote of 2 because theri is no 1.5! Pin
Wamuti1-Sep-12 4:55
Wamuti1-Sep-12 4:55 
GeneralMy vote of 1 Pin
Member 17562317-Aug-12 14:01
Member 17562317-Aug-12 14:01 
GeneralMy vote of 4 Pin
Ashok Hurkat8-Aug-11 3:38
professionalAshok Hurkat8-Aug-11 3:38 
GeneralRe: My vote of 4 Pin
Paul_Williams23-Mar-12 12:35
Paul_Williams23-Mar-12 12:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.