Tuesday, October 28, 2008

Fun with directory security

So for the last couple weeks we have been having a problem with our installer and it’s setting of access rights on directories. This was mostly a problem with vista and well I got made the “vista access rights expert” so that translates into you get to figure out what is wrong.

   15 static void Main(string[] args)
   16 {
   17     string aPath = @"C:\ProgramData\TestApp";
   18     string fPath = Path.Combine(aPath, "files");
   19     Directory.CreateDirectory(fPath);
   20     SetPermissions(aPath);            
   21 }
   22 public static void SetPermissions(string dir)
   23 {
   24     DirectoryInfo info = new DirectoryInfo(dir);
   25     DirectorySecurity ds = info.GetAccessControl();            
   26     ds.AddAccessRule(new FileSystemAccessRule(@"BUILTIN\Users", 
   27                      FileSystemRights.FullControl,
   28                      InheritanceFlags.ContainerInherit,                            
   29                      PropagationFlags.None,
   30                      AccessControlType.Allow));
   31     info.SetAccessControl(ds);            
   32 }

The code started out looking something like this. It adds a security rule for all users to the folder allowing use users access to data on the local system. Problem is that if a program tries to access the files it throws an access denied error. Even though the user’s effective permission to the folder is FullControl. He doesn’t have any access to the files in the folder, and can’t access the files dir at all. After several hours of reading and trying different things all the smart people I drug into help me with the problem came up with three small changes that make it all work without a problem.

   15 static void Main(string[] args)
   16 {
   17     string aPath = @"C:\ProgramData\TestApp";
   18     string fPath = Path.Combine(aPath, "files");
   19     Directory.CreateDirectory(aPath);
   20     SetPermissions(aPath);
   21     Directory.CreateDirectory(fPath);
   22 }
   23 public static void SetPermissions(string dir)
   24 {
   25     DirectoryInfo info = new DirectoryInfo(dir);
   26     DirectorySecurity ds = info.GetAccessControl();
   27     ds.AddAccessRule(new FileSystemAccessRule(@"BUILTIN\Users",
   28                      FileSystemRights.FullControl,
   29                      InheritanceFlags.ObjectInherit |
   30                      InheritanceFlags.ContainerInherit,
   31                      PropagationFlags.None,
   32                      AccessControlType.Allow));
   33     info.SetAccessControl(ds);
   34 }

The changes that needed to be made wore creating the base directory and setting permissions before the sub folder was added. In the set permissions folder there was also a second flag added to the inheritance option of FileSystemAccessRule that changed it so that both files and folders inherited the settings.

No comments: