Configuring Security Permissions and Auditing - Windows PowerShell for Administration: The Personal Trainer (2015)

Windows PowerShell for Administration: The Personal Trainer (2015)

Chapter 5. Configuring Security Permissions and Auditing

As an administrator, some of the most important tasks you perform have to do with configuring and maintaining file-system security. PowerShell makes this easy by providing a simple set of commands for viewing and configuring security descriptors. If you save a transcript of your work or use a script to perform the work, you can easily duplicate your efforts on one computer on other computers in the enterprise.

Commands for Working with Security Descriptors

Commands that help you access file resources include the following:

· Get-Acl Gets objects that represent the security descriptor of a file, registry key, or any other resource with a provider that supports the concept of security descriptors. Use –Audit to get the audit data for the security descriptor from the access control list.

Get-Acl [-Path] FilePaths {AddtlParams}

AddtlParams=
[-Audit] [-Exclude FilesToExclude] [-Include FilesToInclude]
[-AllCentralAccessPolicies]

· Set-Acl Changes the security descriptor of a file, registry key, or any other resource with a provider that supports the concept of security descriptors. Use –AclObject to set the desired security settings.

Set-Acl [-Path] FilePaths [-Aclobject] Security {AddtlParams}

AddtlParams=
[-Exclude FilesToExclude] [-Include FilesToInclude]
[[-CentralAccessPolicy] PolicyName]
[-ClearCentralAccessPolicy]

NOTE On NTFS file system volumes, access permissions control access to files and directories. If you do not have appropriate access permissions, you will not be able to work with files and directories.

Getting and Setting Security Descriptors

Whenever you are working with system resources—such as directories, files, or registry keys—you might want to view or modify a resource’s security descriptor. Use Get-Acl with the –Path parameter to specify the path to resources you want to work with. As with Get-Content, you can use wildcard characters in the path and also include or exclude files using the –Include and –Exclude ­parameters.

Get-Acl returns a separate object containing the security information for each matching file. By default, Get-Acl displays the path to the resource, the owner of the resource, and a list of the access control entries on the resource. The access control list is controlled by the resource owner. To get additional information—including the security group of the owner, a list of auditing entries, and the full security descriptor as an SDDL (Security Descriptor Definition Language) string—format the output as a list as shown in the following example and sample output:

get-acl c:\windows\system32\windowspowershell | format-list

Path: Microsoft.PowerShell.Core\FileSystem::
C:\windows\system32\windowspowershell
Owner : NT AUTHORITY\SYSTEM
Group : NT AUTHORITY\SYSTEM
Access : NT SERVICE\TrustedInstaller Allow FullControl
NT SERVICE\TrustedInstaller Allow 268435456
NT AUTHORITY\SYSTEM Allow FullControl
NT AUTHORITY\SYSTEM Allow 268435456
BUILTIN\Administrators Allow FullControl
BUILTIN\Administrators Allow 268435456
BUILTIN\Users Allow ReadAndExecute, Synchronize
BUILTIN\Users Allow -1610612736
CREATOR OWNER Allow 268435456
Audit :
Sddl : O:SYG:SYD:AI(A;ID;FA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;CIIOID;GA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;ID;FA;;;SY) (A;OICIIOID;GA;;;SY)(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;0x1200a9;;;BU)(A;OICIIOID;GXGR;;;BU)(A;OICIIOID;GA;;;CO)

Here, Get-Acl returns a DirectorySecurity object representing the security descriptor of the C:\Windows\System32\WindowsPowerShell directory. The result is then sent to the Format-List cmdlet.

You can work with files in the same way. Here is an example:

get-acl –include *.txt, *.log –path c:\logs\log* | format-list

Here, Get-Acl returns FileSecurity objects representing the security descriptors of each matching file. The results are then sent to the Format-List cmdlet.

You can work with any properties of security objects separately, including:

· Owner Shows the owner of the resource

· Group Shows the primary group the owner is a member of

· Access Shows the access control rules on the resource

· Audit Shows the auditing rules on the resource

· Sddl Shows the full security descriptor as an SDDL string

NOTE FileSecurity and DirectorySecurity objects have additional properties that aren’t displayed as part of the standard output. To see these properties, send the output to Format-List *. You’ll then see the following note and script properties: ­PSPath (the PowerShell path to the resource), PSParentPath (the PowerShell path to the ­parent resource), PSChildName (the name of the resource), PSDrive (the PowerShell drive on which the resource is located), AccessToString (an alternate representation of the access rules on the resource), and AuditToString (an alternate representation of the audit rules on the resource).

You can use the objects that Get-Acl returns to set the security descriptors on other system resources, including directories, files, and registry keys. To do this, you’ll want to do the following:

1. Open an elevated administrator PowerShell prompt.

2. Obtain a single security descriptor object for a resource that has the security settings you want to use.

3. Use the security descriptor object to establish the desired security settings for another resource.

When you are setting security descriptors in PowerShell, it is a best practice either to specify exactly what you are including, what you are excluding, or both, or to specify only a single resource to modify. Previously, we were working with a log file named log1.txt in the C:\Logs directory. If this log file has a security descriptor that you want to apply to another file, you can do this as shown in the following example:

set-acl –path c:\logs\log2.txt -aclobject (get-acl c:\logs\log1.txt)

Here you use the security descriptor on log1.txt to set the security descriptor for log2.txt.

You can easily extend this technique. In this example, you use the security descriptor on log1.txt to set the security descriptor for all other .txt and .log files in the C:\Logs directory:

$secd = get-acl c:\logs\log1.txt
set-acl –include *.txt, *.log –path c:\logs\* -aclobject $secd

To include files in subdirectories, you need to use Get-ChildItem to obtain reference objects for all the files you want to work with. Here is an example:

$s = get-acl c:\logs\log1.txt

gci c:\logs -recurse –include *.txt, *.log -force |

set-acl -aclobject $s

Here, gci is an alias for Get-ChildItem. You obtain the security descriptor for log1.txt. Next you get a reference to all .txt and .log files in the C:\Logs directory and all subdirectories. Finally, you use the security descriptor on log1.txt to set the security descriptor for all these files.

If you want to work with directories rather than files, you need to limit the results returned by Get-ChildItem. For files and directories, each resource object returned by Get-ChildItem includes a Mode property as shown in the following example and sample output:

get-childitem c:\

Directory: C:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 9/17/2015 2:10 PM apps
da--- 8/16/2015 10:58 AM ClusterStorage
d---- 6/1/2015 8:45 AM data
d---- 10/4/2014 11:50 AM Drivers
d---- 8/3/2014 4:26 PM ExchangeSetupLogs
d---- 4/26/2015 1:29 PM inetpub
d---- 10/4/2015 12:00 PM Intel
d---- 8/22/2014 8:22 AM PerfLogs
d-r-- 5/23/2014 9:26 AM Program Files
d-r-- 5/19/2015 2:57 PM Program Files (x86)
d---- 4/26/2015 2:56 PM root
d-r-- 6/1/2015 9:48 AM Users
d---- 5/19/2015 4:02 PM Windows

The valid values for modes are the following:

· d (directory)

· a (archive)

· r (read-only)

· h (hidden)

· s (system)

Therefore, if you want to work only with directories, you can look for resources where the mode contains a d or is like d*, for example,

where-object {$_.mode -like "d*"}

In addition, if you want to work only with files, you can use

where-object {$_.mode -notlike "d*"}

Knowing this, you can copy the security descriptor on C:\Data to C:\Logs and all its subdirectories as shown in this example:

gci c:\logs -recurse -force | where-object {$_.mode -like "d*"}
| set-acl -aclobject (get-acl c:\data)

Alternatively, you can copy the security descriptor on C:\Data\key.txt to all files in C:\Logs and all its subdirectories, as shown here:

gci c:\logs -recurse -force | where-object {$_.mode –notlike
"d*"} | set-acl -aclobject (get-acl c:\data\key.txt)

NOTE For these examples to work, the directories and files must exist. If you want to try these examples on your computer, create the C:\Data and C:\Logs directories and then add several .txt files to these directories, including a file called key.txt.

Working with Access Rules

As you can see, it is fairly easy and straightforward to copy security descriptors from one resource to another—and more importantly, the same techniques apply to any type of resource that has security descriptors, whether you are working with files, directories, registry keys, or whatever. If you want to create your own security descriptors, we’ll have to dig deeper into the security object model. In this model, access control rules, such as security descriptors, are represented as objects. The Access property of security objects is defined as a collection of authorization rules. With directories and files, these rules have the following object type:

System.Security.AccessControl.FileSystemAccessRule

You can view the individual access control objects that apply to a resource in several ways. One way is to get a security descriptor object and then list the contents of its Access property as shown in the following example and sample output:

$s = get-acl c:\logs
$s.access


FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

FileSystemRights : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : BUILTIN\Users
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : None

FileSystemRights : Modify, Synchronize
AccessControlType : Allow
IdentityReference : NT AUTHORITY\Authenticated Users
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

Here you get the DirectorySecurity object for the C:\Logs directory and then display the contents of its Access property. Although each value listed is an access rule object, you cannot work with each access rule object separately. Note the following in the output:

· FileSystemRights Shows the file system rights being applied

· AccessControlType Shows the access control type as Allow or Deny

· IdentityResource Shows the user or group to which the rule applies

· IsInherited Specifies whether the access rule is inherited

· InheritanceFlags Shows the way inheritance is being applied

· PropagationFlags Specifies whether the access rule will be inherited

Another way to work with each access rule object separately is to use a ForEach loop as shown in this example:

$s = get-acl c:\logs

foreach($a in $s.access) {

#work with each access control object

if ($a.identityreference -like "*administrator*")
{$a | format-list *}
}

FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

Here, you examine each access rule object separately, which allows you to take action on specific access rules. In this example, you look for access rules that apply to administrators.

As an administrator, you’ll often want to perform similar searches to find files and folders that aren’t configured to allow access that might be required to perform backups or other administrative tasks. Previously, we discussed using Get-ChildItem to work with directories and files. For directories and files, each resource object returned by Get-ChildItem includes a Mode property that you can use to work with either directories or files. In the following example and sample output, you list every subdirectory and file under C:\logs that doesn’t allow administrators full control:

$resc = gci c:\logs -recurse -force | where-object `
{$_.mode -notlike "*hs*"}

foreach($r in $resc) {
$s = get-acl $r.FullName
$found = $false

foreach($a in $s.access) {
if (($a.identityreference -like "*administrator*") –and `
($a.filesystemrights –eq "fullcontrol")) {
if ($a.accesscontroltype -eq "allow") { $found = $true }
}
}

if (-not $found) { write-host $r.FullName}
}

C:\logs\backup
C:\logs\backup2
C:\logs\logs
C:\logs\data.ps1
C:\logs\log1.txt
C:\logs\log2.txt
C:\logs\log3.txt
C:\logs\log4.txt
C:\logs\backup\backup
C:\logs\backup\backup\b2

Here, you should run the code using an elevated administrator PowerShell prompt. The $resc variable stores a collection of objects that includes all files and directories under C:\logs, except for files and directories marked as Hidden or System. Using a ForEach loop, you then examine each related resource object. First, you get the access control list for the object by referencing the full name of the object. Then you initialize the $found variable to False so that you can use this variable to track whether a file has the access rights you are looking for.

In the second ForEach loop, you examine each access control object associated with a particular file or folder. If a resource allows administrators full control, you set $found to True. Because you are checking the status of three properties, you use a logical AND to check two properties first. If those properties are both set as expected, you check the third property to see if it is True also. Finally, if $found is not True (meaning it’s False), you write the full name of the file or folder to the output. The result is a list of all files and folders that are not configured so that all administrators have full control.

Configuring File and Directory Permissions

On NTFS volumes, you can assign two types of access permissions to files and directories: Basic and Special. These permissions grant or deny access to users and groups.

Setting Basic Permissions

The basic permissions you can assign to directories and files are shown in Table 5-1 and Table 5-2. These permissions are made up of multiple special permissions. Note the rule flag for each permission because this is the value you must reference when creating an access rule.

TABLE 5-1 Basic Folder Permissions

PERMISSION

DESCRIPTION

RULE FLAG

Full Control

This permission permits reading, writing, changing, and deleting files and subdirectories. If a user has Full Control over a folder, she can delete files in the folder regardless of the permission on the files.

FullControl

Modify

This permission permits reading and writing to files and subdirectories, and it allows deletion of the folder.

Modify

List Folder Contents

This permission permits viewing and listing files and subdirectories as well as executing files; it’s inherited by directories only.

Synchronize

Read & Execute

This permission permits viewing and listing files and subdirectories as well as executing files; it’s inherited by files and directories.

ReadAnd­Execute

Write

This permission permits adding files and subdirectories.

Write

Read

This permission permits viewing and listing files and subdirectories.

Read

TABLE 5-2 Basic File Permissions

PERMISSION

DESCRIPTION

RULE FLAG

Full Control

This permission permits reading, writing, changing, and deleting the file.

FullControl

Modify

This permission permits reading and writing of the file; it allows deletion of the file.

Modify

Read & Execute

This permission permits viewing and accessing the file’s contents as well as executing the file.

ReadAnd­Execute

Write

This permission permits writing to a file. Giving a user permission to write to a file but not to delete it doesn’t prevent the user from deleting the file’s contents.

Write

Read

This permission permits viewing or accessing the file’s contents. Read is the only permission needed to run scripts. Read access is required to access a shortcut and its target.

Read

When you are configuring basic permissions for users and groups, you can specify the access control type as either Allowed or Denied. If a user or group should be granted an access permission, you allow the permission. If a user or group should be denied an access permission, you deny the permission.

You configure basic permissions for resources using access rules. Access rules contain collections of arrays that define

· The user or group to which the rule applies.

· The access permission that applies.

· The allow or deny status.

This means regardless of whether you are adding or modifying rules, the basic syntax for an individual access rule is

"UserOrGroupName", "ApplicablePermission", "ControlType"

where UserOrGroupName is the name of the user or group to which the access rule applies, ApplicablePermission is the basic permission you are applying, and Control­Type specifies the allow or deny status. User and group names are specified in COMPUTER\Name or DOMAIN\Name format. In the following example, you grant full control to BackupOpUser:

"BackupOpUser", "FullControl", "Allow"

When you are working with folders, you can use the basic syntax to configure permissions for folders. You also can use an expanded syntax to configure permissions for a folder and its contents. The expanded syntax for an access rule is

"UserOrGroupName", "ApplicablePermission", "InheritanceFlag", "PropagationFlag","ControlType”

where UserOrGroupName is the name of the user or group to which the access rule applies, ApplicablePermission is the basic permission you are applying, InheritanceFlag controls inheritance, PropagationFlag controls propagation of inherited rules, and ControlType specifies the type of access control. In the following example, you grant full control to DeploymentTesters and apply inheritance to the folder and all its subfolders:

"BackupOpUser", "FullControl", "ContainerInherit", "None", "Allow"

With the inheritance flag, you can specify one of the following flag values:

· None The access rule is not inherited by child objects.

· ContainerInherit The access rule is inherited by subfolders (child container objects).

· ObjectInherit The access rule is inherited by files (child objects).

· ContainerInherit, ObjectInherit The access rule is inherited by files and subfolders (child objects and child container objects).

With the propagation flag, you can specify the following flag values:

· None The access rule is propagated without modification.

· InheritOnly The access rule is propogated to immediate child and child container objects.

· NoPropagateInherit The access rule applies to child objects and to child container objects but not to child objects of child container objects.

· NoPropagateInherit, InheritOnly The access rule applies to child container objects.

You add access rules to a resource using either the SetAccessRule() method or the AddAccessRule() method of the access control object. You remove access rules from a resource using the RemoveAccessRule() method of the access control object. As discussed previously, access rules are defined as having the System.Security.AccessControl.FileSystemAccessRule type.

The easiest way to add and remove access rules is to

1. Get an access control object. This object can be the one that applies to the resource you want to work with or one that applies to a resource that has the closest access control permissions to those you want to use.

2. Create one or more instances of the System.Security.AccessControl.FileSystemAccessRule type, and store the desired permissions in these object instances.

3. Call AddAccessRule() or RemoveAccessRule() to add or remove access rules as necessary. These methods operate on the access control object you retrieved in the first step.

4. To apply the changes you’ve made to an actual resource, you must apply the access control object to a specified resource.

Consider the following example:

set-alias no new-object

$acl = get-acl c:\logs
$perm = "imaginedlands\dev","fullcontrol","allow"

$r = no system.security.accesscontrol.filesystemaccessrule $perm
$acl.addaccessrule($r)
$acl | set-acl c:\logs

Here, you get the access control object on C:\Logs. You store the values for an access rule in a variable called $perm and then create a new instance of the FileSystemAccessRule type for this access rule. The Dev group in the ImaginedLands domain must exist to create the access rule. To add the permission to the access control object you retrieved previously, you call its AddAccessRule() method. Although you could have created additional permissions and added or removed these, you didn’t in this example. Finally, you applied the access control object to a specific resource using Set-Acl.

You can easily extend the previous examples to apply to multiple directories and files as shown in the following example:

set-alias no new-object

$acl = get-acl c:\logs
$perm = "room5\test","fullcontrol","allow"
$r = no system.security.accesscontrol.filesystemaccessrule $perm
$acl.addaccessrule($r)

$resc = gci c:\logs -recurse -force
foreach($f in $resc) {

write-host $f.fullname
$acl | set-acl $f.FullName
}

C:\logs\backup
C:\logs\backup2
C:\logs\logs
C:\logs\data.ps1
C:\logs\log1.txt
C:\logs\log2.txt
C:\logs\log3.txt
C:\logs\log4.txt
C:\logs\backup\backup
C:\logs\backup\backup\b2

Here, you apply an access control list with a modified permission set to every subdirectory of C:\Logs and every file in C:\Logs and its subdirectories. The Test group on the local computer (named Room5) must exist to create the access rule. In the output, you list the names of the directories and files you’ve modified. This helps you keep track of the changes.

Setting Special Permissions

The special permissions you can assign to directories and files are shown in Table 5-3. Because special permissions are combined to make the basic permissions, they are also referred to as atomic permissions. As with basic permissions, note the rule flag for each permission because this is the value you must reference when creating an access rule. When an item has two rule flags, you need to reference only one or the other to set the related special permission.

TABLE 5-3 Special Permissions

PERMISSION

DESCRIPTION

RULE FLAG

Traverse Folder/Execute File

Traverse Folder lets you directly access a folder even if you don’t have explicit access to read the data it contains. Execute File lets you run an executable file.

Traverse, ExecuteFile

List Folder/Read Data

List Folder lets you view file and folder names. Read Data lets you view the contents of a file.

ListDirectory, ReadData

Read Attributes

Lets you read the basic attributes of a file or folder. These attributes include Read-Only, Hidden, System, and Archive.

ReadAttributes

Read Extended Attributes

Lets you view the extended attributes (named data streams) associated with a file. These include Summary fields, such as Title, Subject, and Author, as well as other types of data.

ReadExtendedAttributes

Create Files/Write Data

Create Files lets you put new files in a folder. Write Data ­allows you to overwrite existing data in a file (but not add new data to an existing file because this is covered by Append Data).

CreateFiles, WriteData

Create Folders/Append Data

Create Folders lets you create subfolders within folders. Append Data allows you to add data to the end of an existing file (but not to overwrite existing data because this is covered by Write Data).

CreateFolders, AppendData

Write Attributes

Lets you change the basic ­attributes of a file or folder. These attributes include Read-Only, Hidden, System, and Archive.

WriteAttributes

Write Extended Attributes

Lets you change the extended attributes (named data streams) associated with a file. These include Summary fields, such as Title, Subject, and Author, as well as other types of data.

WriteExtendedAttributes

Delete Subfolders and Files

Lets you delete the contents of a folder. If you have this permission, you can delete the subfolders and files in a folder even if you don’t specifically have Delete permission on the subfolder or file.

DeleteSubdirectoriesAndFiles

Delete

Lets you delete a file or folder. If a folder isn’t empty and you don’t have Delete permission for one of its files or subfolders, you won’t be able to delete it. You can do this only if you have the Delete Subfolders and Files permission.

Delete

Read Permissions

Lets you read all basic and special permissions assigned to a file or folder.

ReadPermissions

Change ­Permissions

Lets you change basic and special permissions assigned to a file or folder.

ChangePermissions

Take Ownership

Lets you take ownership of a file or folder. By default, administrators can always take ownership of a file or folder and can also grant this permission to others.

TakeOwnership

Tables 5-4 and 5-5 show how special permissions are combined to make the basic permissions for files and folders.

Table 5-4 Special Permissions for Folders

SPECIAL PERMISSIONS

FULL CONTROL

MODIFY

READ & EXECUTE

LIST FOLDER CONTENTS

READ

WRITE

Traverse Folder/Execute File

X

X

X

X

List Folder/Read Data

X

X

X

X

X

Read Attributes

X

X

X

X

X

Read Extended ­Attributes

X

X

X

X

X

Create Files/Write Data

X

X

X

Create Folders/Append Data

X

X

X

Write Attributes

X

X

X

Write Extended ­Attributes

X

X

X

Delete Subfolders and Files

X

Delete

X

X

Read Permissions

X

X

X

X

X

X

Change Permissions

X

Take Ownership

X

Table 5-5 Special Permissions for Files

SPECIAL PERMISSIONS

FULL ­CONTROL

MODIFY

READ & EXECUTE

READ

WRITE

Traverse Folder/Execute File

X

X

X

List Folder/Read Data

X

X

X

X

Read Attributes

X

X

X

X

Read Extended Attributes

X

X

X

X

Create Files/Write Data

X

X

X

Create Folders/Append Data

X

X

X

Write Attributes

X

X

X

Write Extended Attributes

X

X

X

Delete Subfolders and Files

X

Delete

X

X

Read Permissions

X

X

X

X

X

Change Permissions

X

Take Ownership

X

You configure special permissions for directories and files in the same way as basic permissions. You add access rules to a resource using either the SetAccessRule() method or the AddAccessRule() method of the access control object. You remove access rules from a resource using the RemoveAccessRule() method of the access control object.

Consider the following example:

set-alias no new-object

$acl = get-acl c:\logs
$p1 = "imaginedlands\dev","executefile","allow"
$r1 = no system.security.accesscontrol.filesystemaccessrule $p1
$acl.addaccessrule($r1)

$p2 = "imaginedlands\dev","listdirectory","allow"
$r2 = no system.security.accesscontrol.filesystemaccessrule $p2
$acl.addaccessrule($r2)

$acl | set-acl c:\logs

Here, you get the access control object on C:\Logs. After you define an access rule and store the related values in $p1, you create a new instance of the FileSystem­AccessRule type and add the permission to the access control object by calling the AddAccessRule() method. After you define a second access rule and store the related values in $p2, you create a new instance of the FileSystemAccessRule type and add the permission to the access control object by calling the AddAccessRule() method. Finally, you apply the access control object to a specific resource using Set-Acl. The Dev group in the ImaginedLands domain must exist to create the access rules.

Taking Ownership

In Windows, the file or directory owner isn’t necessarily the file or directory’s creator. Instead, the file or directory owner is the person who has direct control over the file or directory. File or directory owners can grant access permissions and give other users permission to take ownership of a file or directory.

The way ownership is assigned initially depends on where the file or directory is being created. By default, the user who created the file or directory is listed as the current owner. Ownership can be taken or transferred in several ways. Any administrator can take ownership. Any user or group with the Take Ownership permission can take ownership. Any user who has the Restore Files And Directories right, such as a member of the Backup Operators group, can take ownership as well. Any current owner can transfer ownership to another user as well.

You can take ownership using a file or directory using the SetOwner() method of the access control object. The easiest way to take ownership is to

1. Get an access control object for the resource you want to work with.

2. Get the IdentityReference for the user or group that will take ownership. This user or group must already have permission on the resource (as discussed previously).

3. Call SetOwner to specify that you want the user or group to be the owner.

4. Apply the changes you’ve made to the resource.

Consider the following example:

$acl = get-acl c:\logs
$found = $false
foreach($rule in $acl.access) {
if ($rule.identityreference -like "*administrators*") {
$global:ref = $rule.identityreference; $found = $true; break}
}

if ($found) {
$acl.setowner($ref)
$acl | set-acl c:\logs
}

Here, you get the access control object on C:\Logs. You then examine each access rule on this object, looking for the one that applies to the group you want to work with. If you find a match, you set $ref to the IdentityReference for this group, change $found to $true, and then break out of the ForEach loop. After you break out of the loop, you check to see if $found is True. If it is, you set the ownership permission on the access control object you retrieved previously and then apply the access control object to C:\Logs using Set-Acl.

Configuring File and Directory Auditing

You can use auditing to track what’s happening on your computers. Auditing collects information related to resource usage, such as a file or directory audit. Any time an action occurs that you’ve configured for auditing, the action is written to the system’s security log, where it’s stored for your review. The security log is accessible from Event Viewer. For most auditing changes, you need to be logged on using an account that’s a member of the Administrators group, or you need to be granted the Manage Auditing And Security Log right in Group Policy.

Auditing policies are essential to ensure the security and integrity of your systems. Just about every computer system on the network should be configured with some type of auditing. You can set auditing policies for directories and files using auditing rules.

Audit rules contain collections of arrays that define

· The user or group to which the rule applies.

· The permission usage that is audited.

· The type of auditing.

This means regardless of whether you are adding or modifying rules, the basic syntax for an individual audit rule is

"UserOrGroupName", "PermissionAudited", "AuditType"

where UserOrGroupName is the name of the user or group to which the audit rule applies, PermissionAudited is the basic or special permission you are tracking, and AuditType specifies the type of auditing. Use Success to track successful use of a specified permission. Use Failure to track failed use of a specified permission. Use None to turn off auditing of the specified permission. Use Both to track both failure and success.

As with security permissions, user and group names are specified in COMPUTER\Name or DOMAIN\Name format. In the following example, you track users in the ImaginedLands domain who are trying to access the resource but fail to do so because they don’t have sufficient access permissions:

"IMAGINEDLANDS\USERS", "ReadData", "Failure"

When you are working with folders, you can use the basic syntax to configure auditing for folders. You also can use an expanded syntax to configure auditing for a folder and its contents. The expanded syntax for an access rule is

"UserOrGroupName", "PermissionAudited", "InheritanceFlag", "PropagationFlag","AuditType"

where UserOrGroupName is the name of the user or group to which the access rule applies, PermissionAudited is the basic or special permission you are tracking, InheritanceFlag controls inheritance, PropagationFlag controls propagation of inherited rules, and AuditType specifies the type of auditing. In the following example, you apply an auditing rule to a resource as well as the files and subfolders it contains:

"IMAGINEDLANDS\USERS", "ReadData", "ContainerInherit", "None", "Failure"

With the inheritance flag, you can specify one of the following flag values:

· None The access rule is not inherited by child objects.

· ContainerInherit The access rule is inherited by subfolders (child container objects).

· ObjectInherit The access rule is inherited by files (child objects).

· ContainerInherit, ObjectInherit The access rule is inherited by files and subfolders (child objects and child container objects).

With the propagation flag, you can specify the following flag values:

· None The access rule is propagated without modification.

· InheritOnly The access rule is propogated to immediate child and child container objects.

· NoPropagateInherit The access rule applies to child objects and to child container objects but not to child objects of child container objects.

· NoPropagateInherit, InheritOnly The access rule applies to child container objects.

You add audit rules to a resource using either the SetAuditRule() method or the AddAuditRule() method of the access control object. You remove audit rules from a resource using the RemoveAuditRule() method of the access control object. Audit rules are defined as having the System.Security.AuditControl.FileSystemAuditRule type.

The easiest way to add and remove audit rules is to do the following:

1. Get an access control object. This object can be the one that applies to the resource you want to work with or one that applies to a resource that has the closest audit control permissions to those you want to use.

2. Create one or more instances of the System.Security.AuditControl.FileSystem­AuditRule type, and store the desired auditing settings in these object instances.

3. Call AddAuditRule() or RemoveAuditRule() to add or remove audit rules as necessary. These methods operate on the access control object you retrieved in the first step.

4. Apply the changes you’ve made to an actual resource.

Consider the following example:

set-alias no new-object

$acl = get-acl d:\data
$audit = "imaginedlands\users","readdata","failure"
$r = no system.security.accesscontrol.filesystemauditrule $audit
$acl.addauditrule($r)
$acl | set-acl d:\data

Here, you get the access control object on D:\Data. You store the values for an audit rule in a variable called $audit, and then you create a new instance of the FileSystemAuditRule type with this auditing rule. The Users group in the ImaginedLands domain must exist to create the auditing rule. To add the auditing setting to the access control object you retrieved previously, you call its AddAuditRule() method. Although you could have created additional auditing rules and added or removed these, you didn’t in this example. Finally, you apply the access control object to a specific resource using Set-Acl.

You can easily extend the previous examples to apply to multiple directories and files as shown in the following example:

set-alias no new-object

$acl = get-acl d:\data
$audit = "imaginedlands\users","readdata","failure"
$r = no system.security.accesscontrol.filesystemauditrule $audit
$acl.addauditrule($r)

$resc = gci d:\data -recurse -force
foreach($f in $resc) {

write-host $f.fullname
$acl | set-acl $f.FullName
}

D:\data\backup
D:\data\backup\historydat.txt
D:\data\logs\datlog.log
D:\data\data.ps1
D:\data\transcript1.txt
D:\data\transcript2.txt
D:\data\backup\backup

Here, you apply an auditing rule to every subdirectory of D:\Data and every file in D:\Data and its subdirectories. In the output, you list the names of the directories and files you’ve modified. This helps you keep track of the changes. The Users group in the ImaginedLands domain must exist to create the auditing rule.