Auditing Success and Failure event to folder - windows

I'm using PowerShell to add users to auditing for folders in Windows 10.
I'm using this code to set "EVERYONE" for Auditing.
But I need to do special rules for fail and special rules for Success and Fail, so I need it to save in 2 different lines. - like this picture:
This is the code I'm using:
$Folders = "C:\windows\system32\config"
Foreach ($Folder in $Folders) {
Write-Host "" # Empty line
Write-Host "Applying Auditing for folder", $Folder
Write-Host "" # Empty line
$ACL = Get-Acl $Folder
# Set Auditing for Success event for above Folders for EVeryone group
$PermAudited = "CreateFiles"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAuditRule("Everyone", $PermAudited, "Failure")
$ACL.SetAuditRule($AccessRule)
# Set Auditing for Success event for Top folder
Write-Host $Folder, "for auditing Success event"
$ACL | Set-Acl $Folder
}

You can Specify those rules using the System.Security.AccessControl.FileSystemRights enum, Check the available rules like this:
[enum]::GetNames([System.Security.AccessControl.FileSystemRights])
Basically you need to take a look on one of the Constructors for the FileSystemAuditRule to understand how you need to set it, for your needs I think this is the right one:
FileSystemAuditRule(
string identity,
FileSystemRights fileSystemRights,
AuditFlags flags
)
So, you need to set Rights and AuditFlags, based on your example it should be something like this:
$Rights = "ReadAndExecute","Modify"
$Flags = "Failure"
$AccessRights = [System.Security.AccessControl.FileSystemRights]$Rights
$AuditFlags = [System.Security.AccessControl.AuditFlags]$Flags
Then Set the ACL like this:
$ACL = Get-Acl $Folder
$AccessRule = New-Object System.Security.AccessControl.FileSystemAuditRule("Everyone",$AccessRights, $AuditFlags)
$ACL.SetAuditRule($AccessRule)
Set-Acl -Path $Folder -AclObject $ACL

Related

assign more users to folder on powershell

everyone please help me, I need a command to assign permissions to a folder in the directory tree, conditional on the correct directory name to be assigned. I am trying to write a command line but when assigning a group or a user, it can be assigned but other users are removed, I want to not remove any users.
$mypath = "D:\KIEM TRA1"
$myacl = Get-Acl $mypath
$myaclentry = "EMC0\test.ktnb","readandexecute,write","Allow"
$myaccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
$myacl.SetAccessRule($myaccessrule)
Get-ChildItem -Path "$mypath" -Recurse -Force |
Where-Object { $_.Name -eq 'A' -or $_.Name -eq 'B' } |
Set-Acl -AclObject $myacl -Verbose
I want to do it on a subdirectory and not remove the existing user
I guess what you need is to create a new access rule using 5 parameters, so you can handle inheritance and propagation too.
Try this (always on a set of test folders first of course..)
$mypath = "D:\KIEM TRA1"
$account = "EMC0\test.ktnb"
# see: https://learn.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights
# https://learn.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.inheritanceflags
# https://learn.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.propagationflags
$rule = [System.Security.AccessControl.FileSystemAccessRule]::new($account, "Modify", "ContainerInherit,ObjectInherit", "None", "Allow")
# on older PowerShell versions use:
# $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($account, "Modify", "ContainerInherit,ObjectInherit", "None", "Allow")
# get a list of folder FullNames of subfolders with name 'A' or 'B'
$folders = (Get-ChildItem -Path $mypath -Directory -Recurse | Where-Object { $_.Name -match '^[AB]$' }).FullName
foreach ($directory in $folders) {
# get the current ACL of the folder
$acl = Get-Acl -Path $directory
# add the new rule to the ACL
$acl.AddAccessRule($rule)
$acl | Set-Acl -Path $directory -Verbose
}
Note:
Instead of AddAccessRule(), you might prefer SetAccessRule().
AddAccessRule
This method will add this access rule to the ACL.
If a user has Modify permission and we use AddAccessRule() to create a new rule with Read permission the user will still also have Modify permissions.
SetAccessRule
This method removes any existing access an replaces that access with the specified rule.
If a user has Modify permission and a new rule is created using SetAccessRule() specifying Read permission, that user will now only have Read permission.

Powershell add domain user to ntfs permission to a file

Im trying to write a script where a part of it take ACL from file and adding specific user ntfs permission to modify:
$identity = "$domain\$adname" #In this example $domain='muzi.local $adname='puzi'
$rights = 'Modify'
$inheritance = 'ContainerInherit, ObjectInherit'
$propagation = 'None'
$type = 'Allow'
$Acl = Get-Acl -Path "$bucketdir\$_" #for this example c:\bla.txt
$Acl.AddAccessRule($ACE) #this is where the error output.
Set-Acl -Path "$bucketdir\$_" -AclObject $Acl #code would not get here
Error output:
Exception calling "AddAccessRule" with "1" argument(s): "No flags can be set.
Parameter name: inheritanceFlags"
At C:\Step2.ps1:26 char:3
$Acl.AddAccessRule($ACE)
~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : ArgumentException
Looks like the arguments aren't passing to the function, but if I output them one by one it looks fine
I think you simply forgot to create the new access rule, but also, since you're changing the ACL of a File, not a Directory, you should use the constructor for the new rule which has only 3 parameters, since a file does not have child objects to propagate or inherit access rights:
$identity = "$domain\$adname" #In this example $domain='muzi.local $adname='puzi'
$rights = 'Modify'
$type = 'Allow'
# these do not apply for a File (it has no child objects)
# $inheritance = 'ContainerInherit, ObjectInherit'
# $propagation = 'None'
$file = "$bucketdir\$_" #for this example c:\bla.txt
# create the new AccessRule
$rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, $rights, $type)
$Acl = Get-Acl -Path $file
$Acl.AddAccessRule($rule)
Set-Acl -Path $file -ACLObject $Acl

Powershell CSV Import Error - The object name has bad syntax

Can't seem to figure out what is causing the error with script below with the "New-ADUser" syntax. Not sure if anybody can spot the error?
"New-ADUser : The object name has bad syntax
At D:\ScriptPath\importadusersAndMoveOU.ps1:33 char:3"
The script works if I remove the "$NewOU" variable and have the users imported into the default "users" OU.
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv 'D:\CSVPATH\adusers.csv'
$NewOU = New-ADOrganizationalUnit -Name "ADMINS"
#Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a
variable as below
$DomainName = Get-ADDomain -current LocalComputer
$Username = $User.username
$Password = "TestPassword12345"
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $NewOU+","+$DomainName.DistinguishedName
$upn = $Username+"#"+$DomainName.DNSRoot
#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
#User does not exist then proceed to create the new user account
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName $upn `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Lastname, $Firstname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
Add-ADGroupMember "domain admins" $username
Add-ADGroupMember "enterprise admins" $Username
}
}
The New-ADOrganizationalUnit -Name "ADMINS" command creates a new OU under the default NC head for the domain.
If you want that elsewhere, you should use the -Path <DistinghuisedName of Parent OU> parameter.
However, as Drew Lean already commented, this code does not check if the OU exists before trying to create it, so a quick test might be in order here:
[adsi]::Exists("LDAP://OU=ADMINS,DC=domain,DC=com")
or
Get-ADOrganizationalUnit -Filter "distinguishedName -eq 'OU=ADMINS,DC=domain,DC=com'"
# don't filter on 'Name' because it is more than likely you have several OUs with the same name
Next, the part where you construct the distinguishedName for variable $OU results in a badly formatted string.
$OU = $NewOU+","+$DomainName.DistinguishedName will result in "ADMINS,DC=domain,DC=com" which is not a valid DistinghuishedName, hence the error The object name has bad syntax
Try getting the DN of the existing OU first and if that does not exist, capture it after the creation and store the DistinghuishedName in variable $OU
something like this:
$OU = "OU=ADMINS,DC=domain,DC=com"
if (-not (Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$OU'")) {
$NewOU = New-ADOrganizationalUnit -Name "ADMINS" -PassThru
$OU = $NewOU.DistinghuishedName
}
ps. The Identity parameter for Get-ADOrganizationalUnit must be one of:
A distinguished name
A GUID (objectGUID)
A security identifier (objectSid)
A Security Account Manager account name (sAMAccountName)

How can I use powershell 4.0 set-acl to allow the user to have the same security settings in newly created subdirectories?

When I set user access via set-acl I can loop through all existing subfolders. How do I set it to include future subfolders created under the main folder?
Also... Once the access is set it only displays in 'Advanced' settings for the folders. The first security screen shows the user but shows no access rights.
This is in Windows Server 2012 R2.
$SubFolder = "name"
$UserName = "domain\" + $SubFolder
$Folder = "R:\User Files\" + $SubFolder + "\"
$Acl = Get-Acl $Folder
$Ar = New-Object system.security.accesscontrol.filesystemaccessrule($UserName,"FullControl","Allow")
$Acl.SetAccessRule($Ar)
#Get-Variable
Set-Acl -Path $Folder -AclObject $Acl
$Folder = Get-childItem $Folder
foreach ($TempFolder in $Folder)
{
$Folder = $TempFolder.FullName
$Acl = Get-Acl $Folder
$Ar = New-Object system.security.accesscontrol.filesystemaccessrule($UserName,"FullControl","Allow")
$Acl.SetAccessRule($Ar)
#Get-Variable
Set-Acl -Path $Folder -AclObject $Acl
}
You will need to set your Inheritance and Propagation flags in order for it to affect files and folders within your target. Here's my typical template that I use when I'm working on setting up new ACLs for users:
$Rights = [System.Security.AccessControl.FileSystemRights]"FullControl"
$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]"ObjectInherit,ContainerInherit"
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
#Define the user's account using their samAccountName
$objUser = New-Object System.Security.Principal.NTAccount("samAccountName")
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($objUser, $Rights, $InheritanceFlag, $PropagationFlag, $objType)
$objACL = Get-ACL "C:\Temp"
$objACL.AddAccessRule($objACE)
Set-ACL "C:\Temp" $objACL
The settings here will make future things inherit the settings that you define for the target folder.

Write-Protect System Variables

I'm trying to create a script to write-protect the environment variables and then unlock them whenever we need a script to update them. We've recently had a rash of "admins" that can't read and have been completely wiping out the entire %PATH% variable when told to add a single entry.
I've worked out how we can script that so that there's less risk of such things, but I'd also like to have %PATH% uneditable except for when we need it.
I've successfully created a PowerShell function that does this, however it also prevents me from removing the rule when it needs to be edited. I've left all the default permissions on the key alone, as I ONLY want to add a restriction against editing the keys themselves.
function regLock
{
Write-Host "LOCKING SYSTEM ENVIRONMENT VARIABLES" -ForegroundColor Yellow
$key = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
$acl = Get-Acl $key
$rule = New-Object System.Security.AccessControl.RegistryAccessRule("Administrators", "SetValue", "None", "InheritOnly" , "Deny")
$acl.SetAccessRule($rule)
Set-Acl -AclObject $acl -Path $key
}
function regUnlock
{
Write-Host "UNLOCKING SYSTEM ENVIRONMENT VARIABLES" -ForegroundColor Green
$key = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
$acl = Get-Acl $key
$rule = New-Object System.Security.AccessControl.RegistryAccessRule("Administrators", "SetValue", "None", "InheritOnly" , "Deny")
$acl.RemoveAccessRule($rule)
Set-Acl -AclObject $acl -Path $key
}
Of course if I go into regedit I can remove the lockout key, but that defeats the purpose of keeping them out of places they shouldn't be. I thought the SetValue permission only applied to changing/creating values, not ACL permissions.

Resources