Why you receive a System.Security.SecurityException exception!

Have you ever received an exception like this:

System.Security.SecurityException: xxx.

This exception is thrown whenever you try to access a protected resource while your code doesn’t have the required permissions.

.NET Framework helps protecting computer system from malicious code and software by using a nice feature of CLR called Code Access Security (simply, CAS.) This feature manages the permissions gained by .NET applications, allows code from known vendors and code running from secure locations to run seemlessly without interruption of the CLR, while holds other applications from unknown vendors and applications running from insecure locations (like network shares) to run with restrictions and limitation of access to shared system resources.

A great job from the author is done in the following article:

Understanding .NET Code Access Security

Requesting Admin Approval 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 called Elevation.

Therefore, when a normal user logs on to the system he 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 assigned the latter. When he tries to access a resource 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 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 can 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.


    
    
        
            
                
            
        
    

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. 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. 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 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. Lean 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 illustrates how to request admin approval at the application 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:

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 be failed 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 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 SOFTWAREMicrosoftWindows NTCurrentVersionAppCompatFlagsLayers 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 is -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 these 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!

Microsoft Code Analysis Tool .NET (CAT.NET) v1

CAT.NET is a binary code analysis tool that helps identify common variants of certain prevailing vulnerabilities that can give rise to common attack vectors such as Cross-Site Scripting (XSS), SQL Injection and XPath Injection.

CAT.NET is a snap-in to the Visual Studio IDE that helps you identify security flaws within a managed code (C#, Visual Basic .NET, J#) application you are developing. It does so by scanning the binary and/or assembly of the application, and tracing the data flow among its statements, methods, and assemblies. This includes indirect data types such as property assignments and instance tainting operations. The engine works by reading the target assembly and all reference assemblies used in the application — module-by-module — and then analyzing all of the methods contained within each. It finally displays the issues its finds in a list that you can use to jump directly to the places in your application’s source code where those issues were found. The following rules are currently support by this version of the tool. – Cross Site Scripting – SQL Injection – Process Command Injection – File Canonicalization – Exception Information – LDAP Injection – XPATH Injection – Redirection to User Controlled Site

Download Now