Sunday, May 16, 2010

Protecting assemblies with declarative security

Is difficult for an administrator to know in advance what permissions your assembly needs.  You can specify those permissions previously with declarative security.
CAS can restrict a lot of resources, from printers to files.  For each type of resource to control there is a class associated.  Those classes inherit from CodeAccesSecurityAttibute class, wich have two main properties:
  • Action:  The action to take from the SecurityAction enumeration:
    • SecurityAction.RequestMinimum:  Requires a specific permission for the assembly.  If the assembly doesn't have the permission, an System.Security.Policy.PolicyException will be thrown.
    • SecurityAction.RequestOptional:  Refuses any other permissin not listed in a RequestMinimum or RequestOptional declaration.  If the assembly lacks the permissions declared in a RequestOptional declaration the runtime will not throw an exception.
    • SecurityAction.RequestRefuse:  Reduce the permissions of your assembly.  Doesn't throw any exception.
  • Unrestricted:  A boolean secyfing if all permissions of the class must be granted.
Those declarative permission requirements will be created as an attribute of the assembly.  By example, the following code throws an exception if the assembly lacks the permission to read the C:/boot.ini file:

   1:  using System.Security.Permissions;
   2:   
   3:  [assembly:FileIOPermissionAttibute(SecurtityAction.RequestMinimum, Read=@"C:\boot.ini")]
   4:   
   5:  namespace Example
   6:  {
   7:       class Program
   8:       {
   9:            static void Main(string[] args)
  10:            {
  11:                 Console.WriteLine("Hello");
  12:            }
  13:       }
  14:   
  15:  }

No comments:

Post a Comment

Bookmark and Share