Remove Users group permission for folder inside ProgramData - c#

When I create a folder inside ProgramData folder say Test then I'm seeing below permission for the folder by default for the Users group,
Question, can I remove all the permission for Users group?
I tried below code, but nothing no permission removed,
// This gets the "Authenticated Users" group, no matter what it's called
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
// Create the rules
FileSystemAccessRule fullControlRule = new FileSystemAccessRule(sid, FileSystemRights.FullControl, AccessControlType.Allow);
if (Directory.Exists("C:\\ProgramData\\Test"))
{
// Get your file's ACL
DirectorySecurity fsecurity = Directory.GetAccessControl("C:\\ProgramData\\Test");
// remove the rule to the ACL
fsecurity.RemoveAccessRuleAll(fullControlRule);
// Set the ACL back to the file
Directory.SetAccessControl("C:\\ProgramData\\Test", fsecurity);
}

First, code which should work for your requirement (just tested it myself):
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
...
...
var directoryInfo = new DirectoryInfo(#"C:\ProgramData\Test");
// get the ACL of the directory
var dirSec = directoryInfo.GetAccessControl();
// remove inheritance, copying all entries so that they are direct ACEs
dirSec.SetAccessRuleProtection(true, true);
// do the operation on the directory
directoryInfo.SetAccessControl(dirSec);
// reread the ACL
dirSec = directoryInfo.GetAccessControl();
// get the well known SID for "Users"
var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
// loop through every ACE in the ACL
foreach (FileSystemAccessRule rule in dirSec.GetAccessRules(true, false, typeof(SecurityIdentifier)))
{
// if the current entry is one with the identity of "Users", remove it
if (rule.IdentityReference == sid)
dirSec.RemoveAccessRule(rule);
}
// do the operation on the directory
directoryInfo.SetAccessControl(dirSec);
And now to the details:
First, your idea was good to use a well-known SID and not directly the string. But the Users group is NOT Authenticated Users, so we have to use BuiltinUsersSid
Then, we have to remove the inheritance. In your above screen shot, the entries are grayed out, so not directly changeable. We first have to migrate the inherited entries to direct ones, preserving old entries (if not, the ACL would be empty afterwards).
Then, there can be more than one entry for Users (in fact, there are two). We have to loop through all entries and check if it is one which has the Users sid. Then we remove it.
Some final words:
The ACL / permissioning logic is very complex, and escpecially the inheritance can lead to many problems. But it's getting better now.
I remember the first years after the introduction of inheritance (NT4 => Windows 2000), when many tools (even MS own ones) did not handle it correctly, which produced all sort of problems with invalid / damaged ACLs.

Related

How to distinguish between users and groups assigned to a folder security?

I wrote a simple code to retrieve security information of a folder
the information contain User and groups and the rights they have on the folder
public void GetSecurityRules(DirectoryInfo directoryInfo)
{
DirectorySecurity DSecurity = directoryInfo.GetAccessControl();
AuthorizationRuleCollection Rules = DSecurity.GetAccessRules(true, true, typeof(NTAccount));
foreach (FileSystemAccessRule fileSystemAccessRule in Rules)
{
Console.WriteLine("User/Group name {0}",fileSystemAccessRule.IdentityReference.Value);
Console.WriteLine("Permissions: {0}", fileSystemAccessRule.FileSystemRights.ToString());
}
}
In the line fileSystemAccessRule.IdentityReference.Value I got both Users and Groups but how can i know if the value represent a user or a group?
To the best of my knowledge, the CLR does not expose this information. You will have to p/invoke LsaLookupSids manually and examine the SID_NAME_USE value it will return. CLR calls this function too in order to translate SIDs to account names, but it throws away the SID_NAME_USE values. For code, break out your Reflector, open mscorlib and see how the internal TranslateToNTAccounts function in System.Security.Principal.SecurityIdentifier works.
As an alternative, if you are not going to do such lookups repeatedly, it might be easier to use WMI — query a Win32_Account by SID and examine the SIDType member.

Programmatically created file doesn't always inherit the permissions of the parent folder

(This may be better suited to ServerFault - if so please migrate it!)
We recently upgraded servers from Windows 2003 to Windows 2008. We have now been getting reports that certain PDF files which are dynamically generated are giving "access is denied" messages. I've verified that the folder has "Full Control" to the user group that is being utilized, yet it seems that intermittently files are created without inheriting the parent permissions.
For instance, the parent folder is called Paperwork. The "Users" group is set up to have full control to all files and subfolders within that directory. This works 95% of the time. Once in a while, though, a file will be created and when I view the security permission for that file, the "Users" group does not have Full Control access.
Is there something programmatic that needs to be changed for Windows Server 2008, or is this a configuration issue on the server itself?
take a look at this
try this :
private DirectorySecurity GetDirectorySecurity(string owner)
{
const string LOG_SOURCE = "GetDirectorySecurity";
DirectorySecurity ds = new DirectorySecurity();
System.Security.Principal.NTAccount ownerAccount =
new System.Security.Principal.NTAccount(owner);
ds.SetOwner(ownerAccount);
ds.AddAccessRule(
new FileSystemAccessRule(owner,
FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit,
PropagationFlags.InheritOnly,
AccessControlType.Allow));
//AdminUsers is a List<string> that contains a list from configuration
// That represents the admins who should be allowed
foreach (string adminUser in AdminUsers)
{
ds.AddAccessRule(
new FileSystemAccessRule(adminUser,
FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit,
PropagationFlags.InheritOnly,
AccessControlType.Allow));
}
return ds;
}
ref :
File permissions do not inherit directory permissions

C# code to set a remote share to inherit permissions from its parent directory

I have two machines, call them client and server, in a Windows domain. The server has a shared directory which can be accessed from the client machine. I want to run a C# application on the client which sets the permission on this share to inherit the permissions of the share's parent directory on the server. How do I do this?
I have tried code along the following lines, but I don't think it has the right effect:
DirectoryInfo shareDirectoryInfo = new DirectoryInfo("\\server\share");
DirectorySecurity directorySecurity = shareDirectoryInfo.GetAccessControl();
directorySecurity.SetAccessRuleProtection(false, false);
InheritanceFlags iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
FileSystemAccessRule accessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow);
bool modified;
directorySecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out modified);
if (modified)
{
Directory.SetAccessControl(name, directorySecurity);
}
I guess I don't understand why I have to create a FileSystemAccessRule for the directory - how can I just say inherit from parent?
Thanks for any help! Martin
You can set the folder to inherit from parent by using SetAccessRuleProtection
DirectoryInfo targetFolder = new DirectoryInfo(#"\\server\share");
DirectorySecurity folderSecurity = targetFolder.GetAccessControl(); // Existing security
folderSecurity.SetAccessRuleProtection(false, true); // This sets the folder to inherit
targetFolder.SetAccessControl(folderSecurity);
EDIT: The msdn document explains that if false is sent as the first argument, then the second argument is ignored.

FileSystemRights Issues (C#)

I'm fairly new to file systems and permissions/rights access (aka Access Control List, ACL). While coding with regards to ACL, I am not able to set properties I want to the files. I'm unsure if my understanding of FileSystemRights members are wrong, or I'm totally doing the wrong thing. (And I'm spending quite some time on this part already)
What I'd like to do is change the rights of a file, so that it can only be soelly readable AND cannot be edited, renamed, deleted and copied elsewhere.
Using the MSDN's example, here's what I have so far:
try
{
//Get current identity
WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();
// Add the access control entry to the file.
AddFileSecurity(filename, self.Name, FileSystemRights.Modify, AccessControlType.Deny);
AddFileSecurity(filename, self.Name, FileSystemRights.Write, AccessControlType.Deny);
AddFileSecurity(filename, self.Name, FileSystemRights.ReadAndExecute, AccessControlType.Allow);
// Remove the access control entry from the file.
RemoveFileSecurity(filename, self.Name, FileSystemRights.ReadAndExecute, AccessControlType.Deny);
RemoveFileSecurity(filename, self.Name, FileSystemRights.Read, AccessControlType.Deny);
Console.WriteLine("Done.");
}
catch (Exception e)
{
Console.WriteLine(e);
}
My logic is that:
Add Deny Modify rights (Denying .Modify will cause the file to become unreadable)
Add Deny Write rights
Add Allow ReadAndExecute rights
Remove Deny entry on ReadAndExecute (As .Modify denies ReadAndExecute)
Remove Deny entry on Read (As .Modify denies Read)
Am I doing this part correctly? If not, please advise on what should I do to make the file only readable only and not editable, renamable, deletable and copiable. Many thanks in advance!
Please explain what it is doing wrong. The only thing I see that may be an issue is that you're setting the permissions for yourself, but not the other users, or groups. Perhaps you should iterate through all the groups (admins, users, etc) and disable all but read&execute. Although I think SYSTEM always has full control of all files.

Copy ACL information like XCopy

We recently were forced to move to a new domain server half-way around the world. This may not seem like much of a change, but one of the processes that we run frequently has suddenly gone form a 2-second command to a 5-minute command.
The reason? We are updating the permissions on many directories based on a "template" directory structure.
We've discovered that XCOPY can update the majority of these settings in the same-old-two-second window. The remaining settings, of course, get left off.
What I'm trying to figure out is, how can XCopy do faster what .NET security classes should do natively? Obviously I'm missing something.
What is the best method for copying a directory's ACL information without pinging (or minimal pinging) the domain/Active Directory server?
Here's what I have:
...
DirectorySecurity TemplateSecurity = new DirectorySecurity(TemplateDir, AccessControlSections.All);
...
public static void UpdateSecurity(string destination, DirectorySecurity TemplateSecurity)
{
DirectorySecurity dSecurity = Directory.GetAccessControl(destination);
// Remove previous security settings. (We have all we need in the other TemplateSecurity setting!!)
AuthorizationRuleCollection acl_old = dSecurity.GetAccessRules(true, true, typeof(NTAccount));
foreach (FileSystemAccessRule ace in acl_old)
{
// REMOVE IT IF YOU CAN... if you can't don't worry about it.
try
{
dSecurity.RemoveAccessRule(ace);
}
catch { }
}
// Remove the inheritance for the folders...
// Per the business unit, we must specify permissions per folder.
dSecurity.SetAccessRuleProtection(true, true);
// Copy the permissions from TemplateSecurity to Destination folder.
AuthorizationRuleCollection acl = TemplateSecurity.GetAccessRules(true, true, typeof(NTAccount));
foreach (FileSystemAccessRule ace in acl)
{
// Set the existing security.
dSecurity.AddAccessRule(ace);
try
{
// Remove folder inheritance...
dSecurity.AddAccessRule(new FileSystemAccessRule(
ace.IdentityReference, ace.FileSystemRights,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
ace.AccessControlType));
}
catch { }
}
// Apply the new changes.
Directory.SetAccessControl(destination, dSecurity);
}
Okay... I have a working prototype after A TON OF DIGGING on the internet. Needless to say, there's alot of mis-information about ACL online. I'm not exactly certain if this bit of info will be a godsend, or more mis-information. I'll have to leave that for you, the user, to decide.
What I ended up with is clean, slick, and very, very fast since it doesn't ever TOUCH the domain server. I'm copying the SDDL entries directly. Wait, you say... you can't do that on a directory because you get the dreaded SeSecurityPrivilege error!
Not if you restrict the copy to ONLY the Access Control Lists (ACL).
Here's the code:
public static void UpdateSecurity(string destination, DirectorySecurity templateSecurity)
{
DirectorySecurity dSecurity = Directory.GetAccessControl(destination);
string sddl = templateSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.Access);
try
{
// TOTALLY REPLACE The existing access rights with the new ones.
dSecurity.SetSecurityDescriptorSddlForm(sddl, AccessControlSections.Access);
// Disable inheritance for this directory.
dSecurity.SetAccessRuleProtection(true, true);
// Apply these changes.
Directory.SetAccessControl(destination, dSecurity);
}
catch (Exception ex)
{
// Note the error on the console... we can formally log it later.
Console.WriteLine(pth1 + " : " + ex.Message);
}
// Do some other settings stuff here...
}
Note the AccessControlSections.Access flags on the SDDL methods. That was the magic key to make it all work.

Categories