.NET Security in C#


Since my company does a lot of .NET consultancy, one of ourrecent projects required that file i/o access be denied if the user runningthe application did not have administrator privileges. A lot has been written aboutthe command line utility caspol.exe, however, this can seem a little overthe top and quite complex when considering code groups, policy levels andzone management.

I basically wanted to programmatically check whether the user had the relevant permissions by accessing their windows account. Fortunately, .NETprovides this through the System.Security.Principal namespace. I also wantedto deny access to particular drives – this is done through the namespaceSystem.Security.Permissions.

Below is shown a skeleton example, where if the user is not an administratorthe contents of a text file cannot be read and displayed in a list box:

try
{

//By default deny access to the C Drive…..
CodeAccessPermission UserPermission = new FileIOPermission(FileIOPermissionAccess.AllAccess,@"c:\");

//Check whether the user is part of the administrator group
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;
WindowsIdentity identity = (WindowsIdentity)principal.Identity;

bIsAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);

//Its not, so deny access to the file
if(!bIsAdmin)
{
UserPermission.Deny();
}
else
{
//Do the read
din = ReadTheFile.DoTheRead();
}

if(!bIsAdmin)
{
//Reset deny permissions in current stack frame
CodeAccessPermission.RevertDeny();
}

//If we got this far …. we read in the file
String str;

while ((str=din.ReadLine()) != null)
{
listBox1.Items.Add(str);
}
}
catch (SecurityException exception)
{
//Failed to pass the security checks – so flag up error to user
listBox1.Items.Add("Permission denied accessing file");
}

The zip download file contains the .NET project so you can build and run this example.

Download SecurityExample.zip

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!