Archive for the ‘Security’ Category

h1

Using .NET Code Access Security(CAS)

March 13, 2007

The Common Language Runtime allows to perform only operation which the code is permitted to execute. This is to prevent unauthorized access to protected resources or just to protect code. That is why we use Code Access Security. Using it we can restrict our code for performing some kinds of operation and/or restrict other code to perform operations. For this we can use permission sets – collection of permissions. The permission an be : Full Trust, Local Intranet, Internet, Execution and Nothing

  • Full Trust means that code can be executed on every system which can access this code. This means that code is unrestricted.
  • Local Intranet – its code can be executed from machines which can execute code over the same LAN
  • Internet – Internet restriction for executing this code
  • Execution – this code can only be run but the remote process can not access the resources
  • Nothing – this code can not be executed even from the our machine.

Permission set can include more than one of this permissions except Full Thrust because it include all of other. .NET Configuration Tool allows to create other permissions.

Security Policy is configurable set of rules that the CLR uses to determine the permission level to grant to code. It can be Enterprise, Machine, User and Application Domain . These levels are independent each of other and marks the level on which the code can be used.

Here are some code snippets which we van use when we need to use Code Access Security :

How tho get the permission set of the current machine pragmatically. First wee need to define the policy level on which we need to get permission set. We can use System.Security.SecurityManager class.

IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();

while(policyEnumerator.MoveNext())
{
PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;
if(currentLevel.Label == “Machine”)
{
// Iterate through the permission sets at the Machine level.
IList namedPermissions = currentLevel.NamedPermissionSets;
IEnumerator namedPermission = namedPermissions.GetEnumerator();
// Locate the named permission set.
while(namedPermission.MoveNext())
{

// Write permission set in console

Console.WriteLine(((NamedPermissionSet)namedPermission.Current).Name);
}
}
}

How we can set permission pragmatically

PermissionSet ps = new PermissionSet(PermissionState.None);
ps.AddPermission(new FileIOPermission(
FileIOPermissionAccess.Read | FileIOPermissionAccess.Write ,”C:\\MyFile.txt”));

these are the basic principles of Code Access Security.