0 out of 1 rated this helpful Rate this topic

How to: Request Minimum Permissions by Using the RequestMinimum Flag

Important noteImportant

In the .NET Framework version 4, runtime support has been removed for enforcing the Deny, RequestMinimum, RequestOptional, and RequestRefuse permission requests. These requests should not be used in code that is based on .NET Framework 4 or later. For more information about this and other changes, see Security Changes in the .NET Framework 4.

The RequestMinimum flag enables you to request a minimum set of permissions that your code requires to execute. By contrast, the RequestRefuse flag enables you to refuse permissions by explicitly specifying which ones your code should not be granted.

You can also use the RequestOptional flag to request permissions. In this case, your application will execute even if it does not receive all the permissions that you requested, and a SecurityException is thrown if your application tries to access a protected resource. If you use this type of request, you must enable your code to catch any exceptions that will be thrown if your code is not granted the optional permissions.

The Test example in the following procedure requests FileIOPermission by using the RequestMinimum flag. The example will not run if it is not granted the requested permission. By default, running the example on your desktop will grant it full trust, and it will always run. To test the RequestMinimum flag, the example must be loaded into a partial-trust zone that does not grant FileIOPermission. The steps in the following procedure create a sandbox for the LocalIntranet zone and a test application that requires FileIOPermission. To demonstrate the use of RequestMinimum, the test application is run in the sandbox. When the application is loaded, an exception is thrown.

To Run an Application in a Sandbox

  1. In Visual Studio, create a console application project.

  2. Copy the code from the Example section into the application file. The code creates a sandbox that runs with the LocalIntranet permission set. The LocalIntranet permission set does not include FileIOPermission.

  3. On the Project menu, click Properties, click the Signing tab, and sign the project with a strong name key.

  4. Add a new console application project named Test to the solution.

  5. Copy the following code into the application file for Test. The code requests FileIOPermission as a minimum requirement. If it cannot be granted, a SecurityException is thrown.

    
    using System;
    using System.Security.Permissions;
    using System.IO;
    [assembly: FileIOPermission(SecurityAction.RequestMinimum, Unrestricted=true)]
    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Test is loaded.");
                File.Create("test.txt");
            }
        }
    }
    
    
    
  6. Run the sandbox application. It will try to load and run the test application. When the application is loaded, an exception is thrown with the following message:

    Could not load file or assembly 'Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)":"Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"}. 
    
    
  7. Remove the RequestMinimum requirement by deleting or commenting the line. The example loads and begins execution, but an exception is thrown with the following message:

    Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
    
    

By using the RequestMinimum flag, you can avoid loading the application when it is certain to fail. For more information about how to run applications in a sandbox, see How to: Run Partially Trusted Code in a Sandbox.

The following example creates a sandbox that runs with LocalIntranet permissions.


using System;
using System.Collections;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Reflection;
using System.IO;

namespace SimpleSandboxing
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create the permission set to grant to other assemblies.
            // In this case we are granting the permissions found in the LocalIntranet zone.
            Evidence e = new Evidence();
            e.AddHostEvidence(new Zone(SecurityZone.Intranet));
            PermissionSet pset = SecurityManager.GetStandardSandbox(e);
            // Optionally you can create your own permission set by explicitly adding permissions.
            //     PermissionSet pset = new PermissionSet(PermissionState.None);
            //     pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            //     pset.AddPermission(new UIPermission(PermissionState.Unrestricted));
            AppDomainSetup ads = new AppDomainSetup();
            // Identify the folder to use for the sandbox.
            ads.ApplicationBase = "C:\\Sandbox";
            // Copy the application to be executed to the sandbox.
            File.Copy("..\\..\\..\\HelloWorld\\Bin\\Debug\\HelloWorld.exe", "C:\\sandbox\\HelloWorld.exe", true);

            Evidence hostEvidence = new Evidence();
            // Commenting out the following statement has no effect on the sample.
            // The grant set is determined by the grantSet parameter, not the evidence 
            // for the assembly.  However, the evidence can be used for other reasons, 
            // for example, isolated storage.
            hostEvidence.AddHostEvidence(new Zone(SecurityZone.Intranet));


            // Create the sandboxed domain.
            // You can replace the null parameter with a strong name that identifies full trust assemblies: 
            // GetStrongName(Assembly.GetExecutingAssembly()));  This identifies any assemblies in the folder
            // that are signed with the same strong name as this assembly as being full trust assemblies.
            AppDomain sandbox = AppDomain.CreateDomain(
               "Sandboxed Domain",
               hostEvidence,
               ads,
               pset,
               null);   // Optionally: GetStrongName(Assembly.GetExecutingAssembly()));

            sandbox.ExecuteAssemblyByName("HelloWorld");
        }

        public static StrongName GetStrongName(Assembly assembly)
        {
            if (assembly == null)
                throw new ArgumentNullException("assembly");

            AssemblyName assemblyName = assembly.GetName();
            Debug.Assert(assemblyName != null, "Could not get assembly name");

            // Get the public key blob.
            byte[] publicKey = assemblyName.GetPublicKey();
            if (publicKey == null || publicKey.Length == 0)
                throw new InvalidOperationException("Assembly is not strongly named");

            StrongNamePublicKeyBlob keyBlob = new StrongNamePublicKeyBlob(publicKey);

            // Return the strong name.
            return new StrongName(keyBlob, assemblyName.Name, assemblyName.Version);
        }

    }
}


Did you find this helpful?
(2000 characters remaining)
Community Content Add
Annotations FAQ