P3.NET

Access Control in .NET

(Originally published: 30 Mar 2008)

As of v2 of .NET you can get and set the security of securable objects such as files, folders and registry keys.  Other object types can be added as needed.  While all the access control objects derive from the same base classes they share only a few common elements.  Therefore working with the security of a file requires using different classes than registry keys.  This is an unfortunate limitation of the existing implementation since a generic security handler can not be created with the existing objects.  This article will discuss working with the access control classes in .NET.  While the article will use folders as the target object the concepts (but not the classes) apply to any securable object.  To provide a graphical representation for this discussion open the properties for a folder in Windows Explorer and go to the Security tab.  Click the Advanced button to gain access to the more advanced features we will discuss.

All the core access control types are contained in the System.Security.AccessControl namespace.  The types used to get user/group information are available in System.Security.Principal.

Security Basics

Before we get into the .NET implementation it is important to clarify a few security-related concepts.

Object Rights

Each securable object has a list of operations that it supports.  This list of operations are known as security rights (or just rights).  Rights are generally represented as a set of bit flags internally.  Rights can be combined to form more complex rights.  For example Full Control is a combination of all rights.  Certain rights are shared by all objects including read and modify. 

Due to the variety of rights available, security rights are not exposed directly by the base security classes.  Instead each object-dependent implementation exposes its own set of rights as an enumeration.  We will discuss these rights later.

Identity References

In Windows both users and groups (known as identities) are represented as globally unique values known as SIDs (security identifiers).  SIDs are well-formed but not easily remembered.  All identities are referenced via SIDs internally.  Part of a SID includes the domain or machine that owns the identity.  All SIDs from the same machine/domain share at least a partial identifier.

In .NET the SecurityIdentifier class is used to wrap a SID.  While useful for uniquely identifying a user or group creating an instance of this class directly is rarely done.  Instead this class is generally returned by security-related methods.

Since working with SIDs is not generally useful, other than for uniqueness, .NET provides a more user-friendly version available called NTAccount.  This class is specifically used for users and groups.  It provides the user-friendly name for a SID.  You can easily convert between NTAccount and SecurityIdentifier using the Translate method.  In the few cases where NTAccount can not map the SID to a friendly name it will simply use the SID.  The following example displays the name and SID of the current user.

public void DisplayUser () 

   WindowsIdentity id = WindowsIdentity.GetCurrent(); 

   string name = id.User.Translate(typeof(NTAccount)).Value; 
   string sid = id.User.Translate(typeof(SecurityIdentifier)).Value; 

   Console.WriteLine(“Current User = {0}, [{1}]”, name, sid); 
}

Both NTAccount and SecurityIdentifier derive from IdentityReference.  The base class is generally used in the various security calls to allow either class to be used.  You will almost always want to use NTAccount.

DACLs and SACLs

In Windows there are discretionary access control lists (DACLs) and system access control lists (SACLs).  DACLs specify the rights assigned to identities on an object.  Each entry in the DACL is known as a ACE.  SACLs determine the auditing done on an object.  In most cases you will be working with DACLs. 

In .NET DACLs are known as access rules and SACLs are known as audit rules.  Each access rule contains a security right and the identity that has (or does not have) the right.  .NET uses the abstract class AccessRule to represent an access rule.  Each audit rule contains a security right and the condition under which it is logged (success or failure).  .NET uses the abstract class AuditRule to represent an audit rule.  Neither of these classes are used in most cases as the derived classes provide more information.

In Windows an access rule can either allow or deny a specific right to an identity.  Most rules allow the right.  In the rare case of a deny right it takes precedence over all access rules.  In fact access rules are always listed such that deny rules come first.  A deny rule always overrides an allow rule.  Therefore Windows (and your code) can stop looking for a right as soon as it sees a deny rule for the right.

Object Security

Each securable object has a set of security properties exposed through an ObjectSecurity-derived class.  The derived class exposes methods to access all the security settings of an object including the access and audit rules and the owner.  It is also through this class that we can modify the security of an object.  Unfortunately the base ObjectSecurity class does not expose any of these methods.  This makes working with securable objects in a generic manner difficult.  Instead the base class exposes properties that define the types used to represent the access and audit rules, discussed later. 

The following table defines some common securable objects and their associated object security type.

Object Type ObjectSecurity Class Accessor Class
Active Directory ActiveDirectorySecurity DirectoryEntry
Directory DirectorySecurity Directory, DirectoryInfo
File FileSecurity File, FileInfo
Registry Key RegistrySecurity RegistryKey

Fortunately all the built in classes expose the same set of methods so, other than the type name, working with each type is the same.  There is another solution to this delimma.  Most of the security classes derive from CommonObjectSecurity (which itself derives from ObjectSecurity).  This base class exposes the core methods that we will discuss later.  Therefore you can use CommonObjectSecurity in cases where you might want to work with different object types.  Remember that not all security classes derive from this base class.  ActiveDirectorySecurity is one such case.

So how do you get the object’s security to begin with?  As with the security classes, there is no generic way to get this information.  In the above table the Accessor Class column identifies one or more classes that can be used to get access to an object’s security.  In all cases except Active Directory, the type(s) expose a GetAccessControl method.  Static classes return the object security for the parameter passed to the method.  Instance classes return the object security for the current instance.

The following example gets the security for the C:Windows directory.

DirectorySecurity sec = Directory.GetAccessControl(@”c:Windows”);

 

Access Rules

Each access rule represents: a right, allow/deny flag and the associated identity.  For the standard objects a custom enumerated type is defined to identify the security rights available.  The type of the enumeration is available through the AccessRightType property on the object’s security class, if desired.  The following table defines the enumeration for the standard object types.  We will discuss the last two columns later.

Object Type AccessRightType AccessRuleType AuditRuleType
Active Directory ActiveDirectoryRights ActiveDirectoryAccessRule ActiveDirectoryAuditRule
Directory FileSystemRights FileSystemAccessRule FileSystemAuditRule
File FileSystemRights FileSystemAccessRule FileSystemAuditRule
Registry Key RegistryRights RegistryAccessRule RegistryAuditRule

Starting to notice a pattern yet.  The access right enumerations all end in -Rights.  All the enumerations are marked as flags because several of the rights are combinations of other rights (such as full control).  To get the access rules associated with an object use the GetAccessRules method.  The following example gets the access rules for a directory.

public void PrintDirectorySecurity ( string path ) 

   DirectorySecurity sec = Directory.GetAccessControl(path); 

   … 
}

The GetAccessRules method accepts three parameters: include explicit, include inherited and type of identity.  The first parameter specifies whether rights explicitly assigned to an object are returned.  This is almost always the desired case.  The second parameter specifies where rights inherited from the object’s parent are returned.  The final parameter determines the type of identity reference to be returned.  As discussed earlier there are two standard types: NTAccount and SecurityIdentifier.  For user interfaces the NTAccount is the general choice.

Once we have the access rules we can enumerate them.  The following table lists the important properties of each rule.

Property Description
AccessControlType Determines if this is an allowed or denied right
IdentityReference The user/group with the right
InheritanceFlags Controls how the right is inherited by children
IsInherited Determines if this is an explicit or inherited right
PropagationFlags Determines how the right propagates to children

Notice that the actual rights are not part of the access rule, at least not directly.  Remember that CommonObjectSecurity provides a generic implementation of the security.  However the actual rights are enumerations defined for each object type.  Since CommonObjectSecurity has no way to know what the enumerated values are it doesn’t expose them as a strongly typed property.  The AccessMask property can be used to get the underlying bitmask.  Fortunately each AccessRule-derived class exposes the rights as a strongly typed property named after the enumerated type.  This is the preferred method for getting the rights. 

The following code will list all the rights associated with an object along with some other property values.

public void PrintDirectorySecurity ( string path ) 

   Console.WriteLine(String.Format(“{0,-30} Allowed Inherited {1,-15}”
                            “User/Group”“Right”)); 
   Console.WriteLine(new string(‘-‘70)); 

   DirectorySecurity sec = Directory.GetAccessControl(path); 
   foreach (FileSystemAccessRule rule in 
                sec.GetAccessRules(truetruetypeof(NTAccount))) 
   { 
      Console.WriteLine(“{0,-30} {2} {3} {1,-15:g}”
            rule.IdentityReference, 
            rule.FileSystemRights, 
            rule.AccessControlType == AccessControlType.Allow, 
            rule.IsInherited); 
   }; 
}

There are a couple of important points about enumerating access rules.  Firstly the rights are not always a valid combination of flags from the enumeration.  Secondly an identity can appear more than once in the list.  This can occur for a variety of reasons, inheritance being one of the more common.  Therefore if you want to get all the rights owned by an identity you need to enumerate all rules.  Finally remember that there are both allow and deny rules.  Deny rules come before allow rules and take precedence.

The following method is a simple implementation for getting the rights of a specific identity.  It takes the associated group memberships into account and deny rights.

static FileSystemRights GetObjectRights (
   DirectorySecurity security,
   WindowsIdentity id ) 

   FileSystemRights allowedRights = 0
   FileSystemRights deniedRights = 0

   foreach (FileSystemAccessRule rule in 
              security.GetAccessRules(truetrue, id.User.GetType())) 
   { 
      //If the identity associated with the rule        
        //matches the user or any of their groups  
      if (rule.IdentityReference.Equals(id) ||            
             id.Groups.Contains(rule.IdentityReference)) 
      {
            uint right = (uint)rule.FileSystemRights & 0x00FFFFFF;

         //Filter out the generic rights so we get a           
            //nice enumerated value  
         if (rule.AccessControlType == AccessControlType.Allow) 
            allowedRights |= (FileSystemRights)(right); 
         else 
            deniedRights |= (FileSystemRights)(right); 
      }; 
   }; 

   return allowedRights ^ deniedRights; 
}

The method basically enumerates the access rules of the object and builds up the list of rights for the user (taking their group membership into account).  Denied rights are tracked separately.  After all the rights are determined the allowed rights are returned with any denied rights removed.  Notice the filtering that is going on when adding the rights to the list.  The filter removes the extra bits and generic rights that might be associated with a rule.  These are not supported by the various Rights enumerations and would cause us problems if we wanted to see the string representation.

In the Advanced Security Settings of a folder in Windows Explorer the Permission entries map to these access rules.  You will find that Explorer collapses some of the rules for convenience.  We will discuss the Apply To column later.

Inheritance and Propagation

You can determine if a rule is inherited through the IsInherited property.  Whether a rule is inherited or not is determined by the InheritanceFlags and PropagationFlags properties.  The inheritance flags determine who inherits the rule: child containers (folders), objects (files), both or neither.  The propagation flags determine whether the object (for which you are adding the rule) gets the rule as well.  The following table defines the various combinations of flags and how they map to folder security in Explorer.

PropagationFlags InheritanceFlags Description (Explorer)
None ContainerInherit This folder and subfolders
  ObjectInherit This folder and files
  ContainerInherit | ObjectInherit This folder, subfolders and files
InheritOnly ContainerInherit Subfolders only
  ObjectInherit Files only
  ContainerInherit | ObjectInherit Subfolders and files only

The table left out the propagation flag NoPropagationInherit.  This odd flag can be combined with any of the other entries in the table.  When applied it identifies the rule as applying only to the objects and containers within the target object.  In Explorer this maps to the checkbox below the permission entries (when editing) that says Apply these permissions to objects and/or containers within this container only.

Modifying Access Rules

Modifying access rules can be easy or hard depending on the situation.  To give an identity a new right you create a new access rule and then add it to the object security instance using the AddAccessRule method.  The following example gives the specified user the delete right to a directory.

public void GiveUserDeleteAccess ( string path, WindowsIdentity user ) 

   DirectorySecurity sec = Directory.GetAccessControl(path); 

   FileSystemAccessRule rule = new FileSystemAccessRule(user.User, 
                FileSystemRights.Delete, AccessControlType.Allow); 

   sec.AddAccessRule(rule); 

   Directory.SetAccessControl(path, sec); 
}

Notice the call to SetAccessControl.  The object security instance you obtain from GetAccessControl is a snapshot of the current state of the object.  Changes you make to it do not actually get applied until you call SetAccessControl.  As a result it is when you call SetAccessControl that you are most likely to get an exception such as for unauthorized access or for a missing object.  Whenever you make any changes to an object’s security you must remember to call this method to persist the changes.  In general you will make all the necessary changes before attempting to persist them.

Removing rights is even easier.  When removing rights you have a little more flexibility.  You can remove a specific identity/right rule, all rights for a particular identity or all rights for all users.  To remove a specific identity/right use the RemoveAccessRule.  The following example removes the right we added earlier.

public void TakeUserDeleteAccess ( string path, WindowsIdentity user ) 

   DirectorySecurity sec = Directory.GetAccessControl(path); 

   FileSystemAccessRule rule = new FileSystemAccessRule(
                user.User, FileSystemRights.Delete, 
                AccessControlType.Allow); 

   sec.RemoveAccessRule(rule); 

   Directory.SetAccessControl(path, sec); 
}

To remove all the rights a user has to an object use PurgeAccessRules instead.  It simply requires the identity reference.  You could also the ModifyAccessRule method if you like.  The various methods all basically do the same thing.  In fact methods implemented in derived classes generally call into the base class methods.  Prefer the versions defined in derived classes but do not worry about going out of your way to call them if the base classes are sufficient.

Modifying Inherited Rules  

You can not just modify an inherited rule.  The rule is defined and owned by a parent object.  To modify such a rule you first need to break the inheritance.  When breaking inheritance you have the option of either copying the existing inherited rule or removing it altogether.  In Explorer when you attempt to edit an inherited rule you will notice that it does not allow you to edit the inherited rights.  You can, of course, add new rights. 

Unchecking the Include inheritable permissions from this object’s parent box will display a dialog prompting you to copy or remove the inherited rules.  In .NET you use the SetAccessRuleProtection method on the security object.  The following code demonstrates this method.

DirectorySecurity sec = Directory.GetAccessControl(path); 

//Copy existing inherited rules 
sec.SetAccessRuleProtection(falsetrue); 

//or, remove inherited rules 
sec.SetAccessRuleProtection(falsefalse);

After calling SetAccessRuleProtection you can then modifying all the access rules on the object.

Audit rules  

Audit rules work similar to access rules.  In fact the only real difference is that the members contain -Audit rather than -Access.  Therefore if you want to add a new audit rule use AddAuditRule.  To get the audit rules use GetAuditRules, etc. 

Audit rules have the same properties as well except in lieu of AccessControlType (to define allow and deny rules) they have the AuditFlags property.  Auditing can occur when the operation succeeds, fails or both.  The property is a bitwise flag combination of AuditFlags.  The following table defines the flags.

AuditFlags Description
None No auditing
Success Audit on successful attempts
Failure Audit on failure attempts

Ownership

Each securable object is owned by an identity.  Owning an object gives an identity the special privilege of changing the permissions irrelevant of access rules.  This prevents an owner from being locked out of their own object.

To get the owner of an object use the GetOwner method.  The following example gets the owner of the folder.

public IdentityReference GetDirectoryOwner ( string path ) 

   DirectorySecurity sec = Directory.GetAccessControl(path); 
   return sec.GetOwner(typeof(NTAccount)); 
}

Setting the owner is just as easy using the SetOwner method.  To take ownership of an object requires the right permissions so this method can fail.  The following code makes the Administrators group the owner of the folder.

public void SetDirectoryOwner (     
        string path,     
        IdentityReference newOwner ) 

   DirectorySecurity sec = Directory.GetAccessControl(path); 
             
   sec.SetOwner(newOwner); 
}

 

Summary

There are quite a few features of the .NET access control that we did not cover.  However this article should hopefully get you started in the right direction.

Parallel Test Execution in Visual Studio 2010

Visual Studio 2010 is adding the ability to run tests in parallel.  If you have lots of tests to run and a multi-processor machine then this is a great feature.  It is discussed here.  There have been several posts on the forums about this feature not working but it actually does.  Here are the formal requirements for parallel test execution (you can read the gory details in the link).

  1. Must be running on a multi-processor machine.
  2. Must be running unit tests.  No other test category is supported.
  3. Tests must be thread-safe.  Most unit tests are but tests that use shared resources like a database or the file system may have issues.
  4. Data collections are not allowed. 
  5. Tests must be run locally only.
  6. You must enable the option.  There is no user interface for setting it.

Here is a sample test file that I used to test parallel execution.  It consists of 4 test cases where each test case sleeps for 5 seconds.  When running sequentially this test should take approximately 20 seconds but when running in parallel (assuming 2 processors) it should only take 10. 

[TestMethod] 
public void TestMethod1 () 

   Thread.Sleep(5000); 


[TestMethod] 
public void TestMethod2 () 

   Thread.Sleep(5000); 


[TestMethod] 
public void TestMethod3 () 

   Thread.Sleep(5000); 


[TestMethod] 
public void TestMethod4 () 

   Thread.Sleep(5000); 
}

Here are steps you need to take to get parallel tests to run.  Note that since tests must be run locally you will be updating the local test settings.

  1. Open your test project and double click on the local test settings file (Local.testsettings).
  2. In the Test Settings dialog go to the Data and Diagnostics section and ensure that all the options are unchecked.  This will disable the data collection.

  3. Close the Test Settings dialog.  Now you need to enable parallel test execution.  There is no UI for this so do the following.
    1. Right-click the test settings file in Solution Explorer, select Open With and then XML Editor to open the file in the XML editor.
    2. Go to the Execution element and add the parallel attribute.  You can set it to a specific number of processors or to 0 to allow the tests to run on all processors.

    3. Save and close the file.
  4. Close the solution and reopen it.  The parallel settings are only read when the project loads, at least for Beta 2 and the RC.
  5. Open the Test Results window and group by Result so you can see the parallel execution.
  6. Start debugging (F5 or via the menu).
  7. Open the Test Results window again and you should see the tests running parallel.

A couple of caveats about parallel tests.  Firstly you must close and reopen the solution (or at least the project) in order for changes in the parallel settings to take effect.  Secondly the settings file is rewritten whenever you make changes in the Test Settings dialog.  So if you make changes to the test settings through the UI you will need to modify the settings file manually to get the parallel settings back again.

Parallel test execution is a really neat idea for running unit tests quickly.  Hopefully Microsoft will move the option into the UI so we do not have to go through the manual editing, reload process each time.  Whether that happens before the final release of VS 2010 or not is anyone’s guess.

 

Diskeeper Undelete to the Rescue

For those of you who are not aware Diskeeper Corporation (http://www.diskeeper.com), the creators of the Diskeeper defragmentation tool that I’ve recommended in the past, has a relative new tool out called Undelete.  I received a copy a while back and provided my feedback to Diskeeper and then moved on.  I personally do not use undelete tools.  My philosophy is “if I delete an important file then maybe I’ll pay attention better next time”.  Needless to say I have deleted more than one important document in the past and cursed myself for doing it. Fast forward to recent days while I was at work.  A coworker was cleaning up their hard drive and inadvertently deleted entire directories of important files, most of which were not backed up.  Ignoring the whole “should have had a backup plan” discussion they were in trouble.  A quick search of the Inet revealed a couple of potential undelete tools.  I downloaded one in trial mode and tried it.  Sure enough the files were still there but, since it was a trial, we’d have to buy the product to recover the files.  Then I remembered Diskeeper sending me a copy of their new Undelete tool. I did a quick check and sure enough I had a license for the program and, even better, it comes with Emergency Undelete which allows you to recover files even if Undelete was not already installed.  This is exactly what I needed.  I burned a copy of Emergency Undelete to CD (see below as to why) and ran it on my coworker’s computer.  Sure enough it, really quickly, found the files that were deleted.  Even better is that it was able to restore almost all of them.  We restored all the files to a USB drive and I left my coworker to figure out which files they actually needed.  I went back to my desk: happy that we were able to recover most of the files, and impressed with the speed and ease at which we could do it.  It saved my coworker days of work in trying to recover the data by hand. Without a doubt Emergency Undelete is something I’m keeping around on CD for emergency purposes.  I’m still not comfortable running Undelete-like tools but Emergency Undelete is definitely handy to have.  If nothing else it makes me look like a magician to folks who just lost some critical files.  If you do not have an emergency undelete program then you should get one.  Regular backups are great but they require time and effort to restore.  I, for one, will be recommending Undelete from Diskeeper because I can say first hand that it works as advertised. Caveat: When a file is deleted it is generally just removed from the file system’s directory table.  The actual data is generally still there.  Undelete programs work by scanning the drive and finding these files.  However the operating system treats newly deleted files just like free space so the more data that gets written to a drive the more likely it is that your deleted file will be overwritten.  When you discover that you accidentally deleted a file it is critical that you stop doing anything that might write something to the drive.  This includes running an INet browser, shutting down Windows or even closing programs.  Any of these could save files and overwrite your data.  Go to another program and do the following.
  1. Get an undelete program like Emergency Undelete.
  2. Most good programs are going to allow you to copy the necessary files to removable media like a USB or CD.  Put the undelete program on the media.  A CD is best because you can store the program there and use it whenever you need it.  It saves time and eliminates the need for a secondary computer.
  3. Put the CD (or USB) containing the undelete program into the target computer and run the undelete program.
  4. If all goes well you should see the file(s) you want to recover.  Select the file(s) you want to recover.  If you are unsure then it might be best to recover all the files and then selecting merge the files you actually need.
  5. Now you need to restore them but you cannot restore them to the target machine.  Again any writes might overwrite the very data you are trying to recover.  Restore the files to removable media or a secondary hard drive.  USB works great here.
  6. Once you have recovered all the files you might need you can begin placing them back onto the target machine.  Once you start this step you can assume that any files that were not recovered will be gone.