wasnt nate

Add Everyone Group to a Directory and Registry Key

For my next trick I’ll add the Everyone group to first a directory and then a registry key..
First the everyone group needs to be found in a localizable friendly way

var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

// Print the name for debugging
var group = (NTAccount)everyone.Translate(typeof(NTAccount));
Console.WriteLine("Found group: {0}", group);

Now that the value is known, let’s grant it full access to a folder

var acls = Directory.GetAccessControl(dirName);
acls.PurgeAccessRules(everyone);

acls.AddAccessRule(
  new FileSystemAccessRule(everyone, 
    FileSystemRights.FullControl, 
    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 
    PropagationFlags.InheritOnly, AccessControlType.Allow));

Directory.SetAccessControl(dirName, acls);

Next use that group to update a RegistryKey

var subKey = Registry.LocalMachine.OpenSubKey(Path.Combine(baseKey, subKeyName), true);
var acls = subKey.GetAccessControl();
acls.PurgeAccessRules(everyone);
acls.AddAccessRule(new RegistryAccessRule(everyone, RegistryRights.FullControl, 
  InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
  PropagationFlags.InheritOnly, AccessControlType.Allow));

subKey.SetAccessControl(acls);

Finally pretty print it for debugging

foreach (var item in acls.GetAccessRules(true, true, typeof(NTAccount)))
{
  if (item is RegistryAccessRule)
  {
    var acl = (RegistryAccessRule)item;
    sw.WriteLine("{0} {1} {2}", acl.IdentityReference.ToString(), 
       acl.RegistryRights, acl.AccessControlType);
  }
  else if (item is FileSystemAccessRule)
  {
    var acl = (FileSystemAccessRule)item;
    sw.WriteLine("{0} {1} {2}", acl.IdentityReference.ToString(), 
        acl.FileSystemRights, acl.AccessControlType);
  }
  else
  {
    sw.WriteLine("Not sure what todo with a {0}: {1}", 
        item.GetType(), item.ToString());
  }
}

Leave a Reply