I am trying to learn how to create a new Windows group (using C#) and assign an AccessRule to it by using the local user/group directory services.
I have written the following code which is attempting to firstly create the group, obtain the DirectoryEntry for it, and then creating and assigning a new custom AccessRule:
using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Security.AccessControl;
...
...
var principalContext = new PrincipalContext(ContextType.Machine);
var group = GroupPrincipal.FindByIdentity(principalContext, "groupName");
if (group == null)
{
group = new GroupPrincipal(principalContext)
{
Name = "groupName",
GroupScope = GroupScope.Local,
Description = "groupName description",
SamAccountName = "groupName",
};
group.Save();
}
var path = $"WinNT://{Environment.MachineName}/groupName,group";
var directoryEntry = new DirectoryEntry(path);
var accessRule = new ActiveDirectoryAccessRule(
group.Sid,
ActiveDirectoryRights.WriteProperty,
AccessControlType.Allow,
PermissionsDataSource.CanOverrideExpiredKeysPermissionId,
ActiveDirectorySecurityInheritance.None);
directoryEntry.ObjectSecurity.AddAccessRule(accessRule);
directoryEntry.Options.SecurityMasks = SecurityMasks.Dacl;
directoryEntry.CommitChanges();
The line that is causing me problems at the moment is the following which attempts to add the newly created access rule to the security objects:
directoryEntry.ObjectSecurity.AddAccessRule(accessRule);
The ObjectSecurity property is null. Similarly, the Options property is null. I am therefore not convinced I am creating the GroupPrincipal correctly.
It would be amazing if someone with some experience or knowledge in this area could help me understand what I need to do to be able to add access rules to the group object like I am trying to do above.
Thanks in advance!
P.S. The value
PermissionsDataSource.CanOverrideExpiredKeysPermissionIdis simply an arbitrary Guid which relates to the specific unique permission mapping that the application I am writing uses when checking if the groups a user belongs to has an access rule with this value.
You're working with a local group. Local Windows groups don't have permissions.
You can see this by opening Computer Management (compmgmt.msc) -> Local Users and Groups -> Groups. Right-click on a group and click Properties. You'll see there is no Security tab.