ADSec.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\ADSec.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName ADSec.Import.DoDotSource -Fallback $false
if ($ADSec_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName ADSec.Import.IndividualFiles -Fallback $false
if ($ADSec_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\preimport.ps1"
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\postimport.ps1"
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'ADSec' -Language 'en-US'

function Assert-ADConnection
{
<#
    .SYNOPSIS
        Ensures basic ad connectivity
     
    .DESCRIPTION
        Ensures basic ad connectivity
        Used to ensure subsequent commands have a chance to succeed with the specified server/credential combination.
     
    .PARAMETER Server
        The server / domain to connect to.
         
    .PARAMETER Credential
        The credentials to use for AD operations.
     
    .PARAMETER Cmdlet
        $PSCmdlet of the calling command. Used to handle errors.
     
    .EXAMPLE
        PS C:\> Assert-ADConnection @adParameters -Cmdlet $PSCmdlet
     
        Asserts that AD operations under the specified circumstances are possible.
#>

    [CmdletBinding()]
    Param (
        [string]
        $Server,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [System.Management.Automation.PSCmdlet]
        $Cmdlet
    )
    
    process
    {
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        try { $null = Get-ADDomain @adParameters -ErrorAction Stop }
        catch
        {
            if ($Credential) { $userName = $Credential.UserName }
            else { $userName = '{0}\{1}' -f $env:USERDOMAIN, $env:USERNAME }
            if ($Server) { $target = $Server }
            else { $target = $env:USERDNSDOMAIN }
            
            Stop-PSFFunction -String 'Assert-ADConnection.Failed' -StringValues $target, $userName -EnableException $true -Cmdlet $Cmdlet -FunctionName $Cmdlet.CommandRuntime.ToString() -ErrorRecord $_
        }
    }
}

function Get-LdapObject
{
<#
    .SYNOPSIS
        Use LDAP to search in Active Directory
     
    .DESCRIPTION
        Utilizes LDAP to perform swift and efficient LDAP Queries.
     
    .PARAMETER LdapFilter
        The search filter to use when searching for objects.
        Must be a valid LDAP filter.
     
    .PARAMETER Properties
        The properties to retrieve.
        Keep bandwidth in mind and only request what is needed.
     
    .PARAMETER SearchRoot
        The root path to search in.
        This generally expects either the distinguished name of the Organizational unit or the DNS name of the domain.
        Alternatively, any legal LDAP protocol address can be specified.
     
    .PARAMETER Configuration
        Rather than searching in a specified path, switch to the configuration naming context.
     
    .PARAMETER Raw
        Return the raw AD object without processing it for PowerShell convenience.
     
    .PARAMETER PageSize
        Rather than searching in a specified path, switch to the schema naming context.
     
    .PARAMETER SearchScope
        Whether to search all OUs beneath the target root, only directly beneath it or only the root itself.
     
    .PARAMETER Server
        The server / domain to connect to.
     
    .PARAMETER Credential
        The credentials to use.
     
    .EXAMPLE
        PS C:\> Get-LdapObject -LdapFilter '(PrimaryGroupID=516)'
         
        Searches for all objects with primary group ID 516 (hint: Domain Controllers).
#>

    [CmdletBinding(DefaultParameterSetName = 'SearchRoot')]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $LdapFilter,
        
        [string[]]
        $Properties = "*",
        
        [Parameter(ParameterSetName = 'SearchRoot')]
        [string]
        $SearchRoot,
        
        [Parameter(ParameterSetName = 'Configuration')]
        [switch]
        $Configuration,
        
        [switch]
        $Raw,
        
        [ValidateRange(1, 1000)]
        [int]
        $PageSize = 1000,
        
        [System.DirectoryServices.SearchScope]
        $SearchScope = 'Subtree',
        
        [string]
        $Server,
        
        [System.Management.Automation.PSCredential]
        $Credential
    )
    
    begin
    {
        $searcher = New-Object system.directoryservices.directorysearcher
        $searcher.PageSize = $PageSize
        $searcher.SearchScope = $SearchScope
        if ($Credential)
        {
            $searcher.SearchRoot.Username = $Credential.UserName
            try { $searcher.SearchRoot.Password = $Credential.GetNetworkCredential().Password }
            catch { Stop-PSFFunction -String 'Get-LdapObject.CredentialError' -ErrorRecord $_ -Cmdlet $PSCmdlet -EnableException $true }
        }
        
        if ($SearchRoot)
        {
            if ($SearchRoot -like "LDAP://*") { $searcher.SearchRoot.Path = $SearchRoot }
            elseif ($SearchRoot -notlike "*=*") { $searcher.SearchRoot.Path = "LDAP://DC={0}" -f ($SearchRoot -split "\." -join ",DC=") }
            else { $searcher.SearchRoot.Path = "LDAP://$($SearchRoot)" }
        }
        
        if ($Configuration)
        {
            $searcher.SearchRoot.Path = "LDAP://CN=Configuration,{0}" -f $searcher.SearchRoot.distinguishedName[0]
        }
        if ($Server -and ($searcher.SearchRoot.Path -notmatch '^LDAP://[\w\.]+/'))
        {
            $searcher.SearchRoot.Path = $searcher.SearchRoot.Path -replace '^LDAP://', "LDAP://$Server/"
        }
        Write-PSFMessage -String Get-LdapObject.SearchRoot -StringValues $SearchScope, $searcher.SearchRoot.Path -Level Debug
        
        $searcher.Filter = $LdapFilter
        
        foreach ($property in $Properties)
        {
            $null = $searcher.PropertiesToLoad.Add($property)
        }
        
        Write-PSFMessage -String Get-LdapObject.Searchfilter -StringValues $LdapFilter -Level Debug
    }
    process
    {
        try
        {
            foreach ($ldapobject in $searcher.FindAll())
            {
                if ($Raw)
                {
                    $ldapobject
                    continue
                }
                $resultHash = @{ }
                foreach ($key in $ldapobject.Properties.Keys)
                {
                    # Write-Output verwandelt Arrays mit nur einem Wert in nicht-Array Objekt
                    $resultHash[$key] = $ldapobject.Properties[$key] | Write-Output
                }
                if ($resultHash.ContainsKey("ObjectClass")) { $resultHash["PSTypeName"] = $resultHash["ObjectClass"] }
                [pscustomobject]$resultHash
            }
        }
        catch
        {
            Stop-PSFFunction -String 'Get-LdapObject.SearchError' -ErrorRecord $_ -Cmdlet $PSCmdlet -EnableException $true
        }
    }
}

function Disable-AdsInheritance {
    <#
    .SYNOPSIS
        Disables inheritance on an Active Directoey object.
     
    .DESCRIPTION
        Disables inheritance on an Active Directoey object.
     
    .PARAMETER Path
        The distinguished name of the object to process.
     
    .PARAMETER DiscardInherited
        By default, all previously inherited access rules will be preserved as new explicit rules.
        Using this parameter, all inherited access rules will be discarded instead.
     
    .PARAMETER Server
        The server / domain to connect to.
         
    .PARAMETER Credential
        The credentials to use for AD operations.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Get-ADUser administrator | Disable-AdsInheritance
     
        Disables inheritance on the administrator object.
     
    .EXAMPLE
        PS C:\> Get-ADComputer -LDAPFilter '(primaryGroupID=516)' | Disable-AdsInheritance -DiscardInherited
     
        Disables inheritance on all domain controllers, remove all previously inherited access rules.
#>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Alias('DistinguishedName')]
        [string[]]
        $Path,
        
        [switch]
        $DiscardInherited,
        
        [string]
        $Server,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin {
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        Assert-ADConnection @adParameters -Cmdlet $PSCmdlet
        
        # Wrap as nested pipeline to avoid asserting connection each time
        $getCmd = { Get-AdsAcl @adParameters -EnableException:$EnableException }
        $getAdsAcl = $getCmd.GetSteppablePipeline()
        $getAdsAcl.Begin($true)
        
        $setCmd = { Set-AdsAcl @adParameters -EnableException:$EnableException }
        $setAdsAcl = $setCmd.GetSteppablePipeline()
        $setAdsAcl.Begin($true)
    }
    process {
        foreach ($pathItem in $Path) {
            Write-PSFMessage -String 'Disable-AdsInheritance.Processing' -StringValues $pathItem -Target $pathItem
            try { $aclObject = ($getAdsAcl.Process($pathItem))[0] }
            catch { Stop-PSFFunction -String 'Disable-AdsInheritance.ReadAcl.Failed' -StringValues $pathItem -ErrorRecord $_ -EnableException $EnableException -Continue -Target $pathItem }
            
            $changedAnything = $false
            if (-not $aclObject.AreAccessRulesProtected) {
                $aclObject.SetAccessRuleProtection($true, (-not $DiscardInherited))
                $changedAnything = $true
            }
            
            if (-not $changedAnything) {
                Write-PSFMessage -String 'Disable-AdsInheritance.NoChange.Skipping' -StringValues $pathItem -Target $pathItem
                continue
            }
            
            Invoke-PSFProtectedCommand -ActionString 'Disable-AdsInheritance.Updating.Acl' -Target $pathItem -ScriptBlock {
                $setAdsAcl.Process($aclObject)
            } -EnableException $EnableException.ToBool() -PSCmdlet $PSCmdlet -Continue
        }
    }
    end {
        $getAdsAcl.End()
        $setAdsAcl.End()
    }
}

function Enable-AdsInheritance
{
<#
    .SYNOPSIS
        Enables inheritance on an Active Directoey object.
     
    .DESCRIPTION
        Enables inheritance on an Active Directoey object.
     
    .PARAMETER Path
        The distinguished name of the object to process.
     
    .PARAMETER RemoveExplicit
        By default, all previous access rules will be preserved.
        Using this parameter, all explicit access rules will instead be removed.
     
    .PARAMETER Server
        The server / domain to connect to.
         
    .PARAMETER Credential
        The credentials to use for AD operations.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Get-ADUser administrator | Enable-AdsInheritance
     
        Enables inheritance on the administrator object.
     
    .EXAMPLE
        PS C:\> Get-ADComputer -LDAPFilter '(primaryGroupID=516)' | Enable-AdsInheritance -RemoveExplicit
     
        Remove all explicit permissions for deletion.
#>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Alias('DistinguishedName')]
        [string[]]
        $Path,
        
        [switch]
        $RemoveExplicit,
        
        [string]
        $Server,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        Assert-ADConnection @adParameters -Cmdlet $PSCmdlet
        
        # Wrap as nested pipeline to avoid asserting connection each time
        $getCmd = { Get-AdsAcl @adParameters -EnableException:$EnableException }
        $getAdsAcl = $getCmd.GetSteppablePipeline()
        $getAdsAcl.Begin($true)
        
        $setCmd = { Set-AdsAcl @adParameters -EnableException:$EnableException }
        $setAdsAcl = $setCmd.GetSteppablePipeline()
        $setAdsAcl.Begin($true)
    }
    process
    {
        foreach ($pathItem in $Path)
        {
            Write-PSFMessage -String 'Enable-AdsInheritance.Processing' -StringValues $pathItem -Target $pathItem
            try { $aclObject = ($getAdsAcl.Process($pathItem))[0] }
            catch { Stop-PSFFunction -String 'Enable-AdsInheritance.ReadAcl.Failed' -StringValues $pathItem -ErrorRecord $_ -EnableException $EnableException -Continue -Target $pathItem }
            
            $changedAnything = $false
            if ($aclObject.AreAccessRulesProtected)
            {
                $aclObject.SetAccessRuleProtection($false, $true)
                $changedAnything = $true
            }
            if ($RemoveExplicit -and ($aclObject.Access | Where-Object IsInherited -EQ $false))
            {
                ($aclObject.Access) | Where-Object IsInherited -EQ $false | & {
                    process
                    {
                        Write-PSFMessage -Level Debug -String 'Enable-AdsInheritance.AccessRule.Remove' -StringValues $_.IdentityReference, $_.ActiveDirectoryRights, $_.AccessControlType -Target $pathItem
                        $null = $aclObject.RemoveAccessRule($_)
                    }
                }
                $changedAnything = $true
            }
            
            if (-not $changedAnything)
            {
                Write-PSFMessage -String 'Enable-AdsInheritance.NoChange.Skipping' -StringValues $pathItem -Target $pathItem
                continue
            }
            
            Invoke-PSFProtectedCommand -ActionString 'Enable-AdsInheritance.Updating.Acl' -Target $pathItem -ScriptBlock {
                $setAdsAcl.Process($aclObject)
            } -EnableException $EnableException.ToBool() -PSCmdlet $PSCmdlet -Continue
        }
    }
    end
    {
        $getAdsAcl.End()
        $setAdsAcl.End()
    }
}

function Get-AdsAcl
{
<#
    .SYNOPSIS
        Reads the ACL from an AD object.
     
    .DESCRIPTION
        Reads the ACL from an AD object.
        Allows specifying the server to ask.
     
    .PARAMETER Path
        The DistinguishedName path to the item.
     
    .PARAMETER Server
        The server / domain to connect to.
         
    .PARAMETER Credential
        The credentials to use for AD operations.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .EXAMPLE
        PS C:\> Get-ADUser -Filter * | Get-AdsAcl
         
        Returns the ACL of every user in the domain.
#>

    [OutputType([System.DirectoryServices.ActiveDirectorySecurity])]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Alias('DistinguishedName')]
        [string[]]
        $Path,
        
        [string]
        $Server,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        Assert-ADConnection @adParameters -Cmdlet $PSCmdlet
    }
    process
    {
        if (Test-PSFFunctionInterrupt) { return }
        
        foreach ($pathItem in $Path)
        {
            if (-not $pathItem) { continue }
            Write-PSFMessage -String 'Get-AdsAcl.Processing' -StringValues $pathItem
            
            try { $adObject = Get-ADObject @adParameters -Identity $pathItem -Properties ntSecurityDescriptor }
            catch { Stop-PSFFunction -String 'Get-AdsAcl.ObjectError' -StringValues $pathItem -Target $pathItem -EnableException $EnableException -Cmdlet $PSCmdlet -ErrorRecord $_ -Continue }
            $aclObject = $adObject.ntSecurityDescriptor
            Add-Member -InputObject $aclObject -MemberType NoteProperty -Name DistinguishedName -Value $adObject.DistinguishedName -Force
            $aclObject
        }
    }
}

function Get-AdsOrphanAce
{
<#
    .SYNOPSIS
        Returns list of all access rules that have an unresolveable identity.
     
    .DESCRIPTION
        Returns list of all access rules that have an unresolveable identity.
        This is aimed at identifying and help remediating orphaned SIDs in active directory.
     
    .PARAMETER Path
        The full distinguished name to the object to scan.
     
    .PARAMETER ExcludeDomainSID
        SIDs from the specified domain SIDs will be ignored.
        Use this to safely handle one-way trust where ID resolution is impossible for some IDs.
     
    .PARAMETER IncludeDomainSID
        If specified, only unresolved identities from the specified SIDs will be listed.
        Use this to safely target only rules from your owned domains in the targeted domain.
     
    .PARAMETER Server
        The server / domain to connect to.
         
    .PARAMETER Credential
        The credentials to use for AD operations.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .EXAMPLE
        PS C:\> Get-ADObject -LDAPFillter '(objectCategory=*)' | Get-AdsOrphanAce
     
        Scans all objects in the current domain for orphaned access rules.
#>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true, Mandatory = $true)]
        [string[]]
        $Path,
        
        [string[]]
        $ExcludeDomainSID,
        
        [string[]]
        $IncludeDomainSID,
        
        [string]
        $Server,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        Assert-ADConnection @adParameters -Cmdlet $PSCmdlet
        
        function Write-Result
        {
            [CmdletBinding()]
            param (
                [string]
                $Path,
                
                [System.DirectoryServices.ActiveDirectoryAccessRule]
                $AccessRule
            )
            
            [PSCustomObject]@{
                PSTypeName = 'ADSec.AccessRule'
                Path       = $Path
                Identity   = $AccessRule.IdentityReference
                ADRights   = $AccessRule.ActiveDirectoryRights
                Type       = $AccessRule.AccessControlType
                ObjectType = $AccessRule.ObjectType
                InheritedOpectType = $AccessRule.InheritedObjectType
                Rule       = $AccessRule
            }
        }
        
        # Wrap as nested pipeline to avoid asserting connection each time
        $scriptCmd = { Get-AdsAcl @adParameters -EnableException:$EnableException }
        $getAdsAcl = $scriptCmd.GetSteppablePipeline()
        $getAdsAcl.Begin($true)
    }
    process
    {
        foreach ($pathItem in $Path)
        {
            try { $acl = $getAdsAcl.Process($pathItem) }
            catch { Stop-PSFFunction -String 'Get-AdsOrphanAce.Read.Failed' -StringValues $pathItem -EnableException $EnableException -ErrorRecord $_ -Cmdlet $PSCmdlet -Continue }
            if (-not $acl) { Stop-PSFFunction -String 'Get-AdsOrphanAce.Read.Failed' -StringValues $pathItem -EnableException $EnableException -Cmdlet $PSCmdlet -Continue }
            
            foreach ($rule in $acl.Access)
            {
                if ($rule.IsInherited) { continue }
                if ($rule.IdentityReference -is [System.Security.Principal.NTAccount]) { continue }
                if ($rule.IdentityReference.AccountDomainSID.Value -in $ExcludeDomainSID) { continue }
                if ($IncludeDomainSID -and ($rule.IdentityReference.AccountDomainSID.Value -notin $IncludeDomainSID)) { continue }
                
                try { $null = $rule.IdentityReference.Translate([System.Security.Principal.NTAccount]) }
                catch { Write-Result -Path $pathItem -AccessRule $rule }
            }
        }
    }
    end
    {
        $getAdsAcl.End()
    }
}

function Remove-AdsOrphanAce
{
<#
    .SYNOPSIS
        Removes all access rules that have an unresolveable identity.
     
    .DESCRIPTION
        Removes all access rules that have an unresolveable identity.
        This is aimed at identifying and remediating orphaned SIDs in active directory.
     
    .PARAMETER Path
        The full distinguished name to the object to clean.
     
    .PARAMETER ExcludeDomainSID
        SIDs from the specified domain SIDs will be ignored.
        Use this to safely handle one-way trust where ID resolution is impossible for some IDs.
     
    .PARAMETER IncludeDomainSID
        If specified, only unresolved identities from the specified SIDs will be listed.
        Use this to safely target only rules from your owned domains in the targeted domain.
     
    .PARAMETER Server
        The server / domain to connect to.
         
    .PARAMETER Credential
        The credentials to use for AD operations.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Get-ADObject -LDAPFillter '(objectCategory=*)' | Remove-AdsOrphanAce
     
        Purges all objects in the current domain from orphaned access rules.
#>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param (
        [Parameter(ValueFromPipeline = $true, Mandatory = $true)]
        [string[]]
        $Path,
        
        [string[]]
        $ExcludeDomainSID,
        
        [string[]]
        $IncludeDomainSID,
        
        [string]
        $Server,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        Assert-ADConnection @adParameters -Cmdlet $PSCmdlet
        
        function Write-Result
        {
            [CmdletBinding()]
            param (
                [string]
                $Path,
                
                [System.DirectoryServices.ActiveDirectoryAccessRule]
                $AccessRule,
                
                [ValidateSet('Deleted', 'Failed')]
                [string]
                $Action,
                
                [System.Management.Automation.ErrorRecord]
                $ErrorRecord
            )
            
            [PSCustomObject]@{
                PSTypeName = 'ADSec.AccessRule'
                Path       = $Path
                Identity   = $AccessRule.IdentityReference
                Action       = $Action
                ADRights   = $AccessRule.ActiveDirectoryRights
                Type       = $AccessRule.AccessControlType
                ObjectType = $AccessRule.ObjectType
                InheritedOpectType = $AccessRule.InheritedObjectType
                Rule       = $AccessRule
                Error       = $ErrorRecord
            }
        }
        
        # Wrap as nested pipeline to avoid asserting connection each time
        $scriptCmd = { Get-AdsAcl @adParameters -EnableException:$EnableException }
        $getAdsAcl = $scriptCmd.GetSteppablePipeline()
        $getAdsAcl.Begin($true)
    }
    process
    {
        foreach ($pathItem in $Path)
        {
            Write-PSFMessage -Level Verbose -String 'Remove-AdsOrphanAce.Searching' -StringValues $pathItem
            try { $acl = $getAdsAcl.Process($pathItem) | Write-Output }
            catch { Stop-PSFFunction -String 'Remove-AdsOrphanAce.Read.Failed' -StringValues $pathItem -EnableException $EnableException -ErrorRecord $_ -Cmdlet $PSCmdlet -Continue }
            if (-not $acl) { Stop-PSFFunction -String 'Remove-AdsOrphanAce.Read.Failed' -StringValues $pathItem -EnableException $EnableException -Cmdlet $PSCmdlet -Continue }
            
            $rulesToPurge = foreach ($rule in $acl.Access)
            {
                if ($rule.IsInherited) { continue }
                if ($rule.IdentityReference -is [System.Security.Principal.NTAccount]) { continue }
                if ($rule.IdentityReference.AccountDomainSID.Value -in $ExcludeDomainSID) { continue }
                if ($IncludeDomainSID -and ($rule.IdentityReference.AccountDomainSID.Value -notin $IncludeDomainSID)) { continue }
                
                try { $null = $rule.IdentityReference.Translate([System.Security.Principal.NTAccount]) }
                catch
                {
                    $null = $acl.RemoveAccessRule($rule)
                    $rule
                }
            }
            if (-not $rulesToPurge)
            {
                Write-PSFMessage -Level Verbose -String 'Remove-AdsOrphanAce.NoOrphans' -StringValues $pathItem
                continue
            }
            
            Invoke-PSFProtectedCommand -ActionString 'Remove-AdsOrphanAce.Removing' -ActionStringValues ($rulesToPurge | Measure-Object).Count -Target $pathItem -ScriptBlock {
                try
                {
                    Set-ADObject @adParameters -Identity $pathItem -Replace @{ ntSecurityDescriptor = $acl } -ErrorAction Stop
                    foreach ($rule in $rulesToPurge) { Write-Result -Path $pathItem -AccessRule $rule -Action Deleted }
                }
                catch
                {
                    foreach ($rule in $rulesToPurge) { Write-Result -Path $pathItem -AccessRule $rule -Action Failed -ErrorRecord $_ }
                    throw
                }
            } -EnableException $EnableException.ToBool() -PSCmdlet $PSCmdlet -Continue
        }
    }
    end
    {
        $getAdsAcl.End()
    }
}

function Set-AdsAcl
{
<#
    .SYNOPSIS
        Updates the ACL on an active directory object.
     
    .DESCRIPTION
        Updates the ACL on an active directory object.
        Used to manage AD delegation.
     
    .PARAMETER Path
        The path / distinguishedname to the object to manage.
     
    .PARAMETER AclObject
        The acl to apply
     
    .PARAMETER Server
        The server / domain to connect to.
         
    .PARAMETER Credential
        The credentials to use for AD operations.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .EXAMPLE
        PS C:\> $acl | Set-AdsAcl
     
        Applies the acl object(s) stored in $acl.
        Assumes that 'Get-AdsAcl' was used to retrieve the data originally.
     
    .EXAMPLE
        PS C:\> Set-AdsAcl -AclObject $acl -Path $dn -Server fabrikam.com
     
        Updates the acl on the object stored in $dn within the fabrikam.com domain.
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        [Alias('DistinguishedName')]
        [string]
        $Path,
        
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [System.DirectoryServices.ActiveDirectorySecurity]
        $AclObject,
        
        [string]
        $Server,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        Assert-ADConnection @adParameters -Cmdlet $PSCmdlet
    }
    process
    {
        if (-not $Path)
        {
            if ($AclObject.DistinguishedName) { $Path = $AclObject.DistinguishedName }
            else
            {
                Stop-PSFFunction -String 'Set-AdsAcl.NoPath' -Target $AclObject -EnableException $EnableException -Category InvalidArgument
                return
            }
        }
        Invoke-PSFProtectedCommand -ActionString 'Set-AdsAcl.SettingSecurity' -Target $Path -ScriptBlock {
            Set-ADObject @adParameters -Identity $Path -Replace @{ ntSecurityDescriptor = $AclObject } -ErrorAction Stop
        } -EnableException $EnableException.ToBool() -PSCmdlet $PSCmdlet
    }
}

function Set-AdsOwner
{
<#
    .SYNOPSIS
        Changes the owner of the specified AD object to the target identity.
     
    .DESCRIPTION
        Changes the owner of the specified AD object to the target identity.
     
    .PARAMETER Path
        Path to the object to update
     
    .PARAMETER Identity
        Identity to make the new owner.
     
    .PARAMETER WinRMFailover
        Whether on execution error it should try again using WinRM.
        Default-Value determined using the configuration setting 'ADSec.WinRM.FailOver'
     
    .PARAMETER Server
        The server / domain to connect to.
     
    .PARAMETER Credential
        The credentials to use for AD operations.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Set-AdsOwner -Path $dn -Identity 'contoso\Domain Admins'
         
        Makes the domain admins owner of the path specified in $dn
#>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseUsingScopeModifierInNewRunspaces', '')]
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Alias('DistinguishedName')]
        [string[]]
        $Path,
        
        [Parameter(Mandatory = $true)]
        [string]
        $Identity,
        
        [switch]
        $WinRMFailover = (Get-PSFConfigValue -FullName 'ADSec.WinRM.FailOver'),
        
        [string]
        $Server,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        Assert-ADConnection @adParameters -Cmdlet $PSCmdlet
        
        if ($Identity -as [System.Security.Principal.SecurityIdentifier])
        {
            $idReference = [System.Security.Principal.SecurityIdentifier]$Identity
        }
        else
        {
            $idReference = [System.Security.Principal.NTAccount]$Identity
            try { $null = $idReference.Translate([System.Security.Principal.SecurityIdentifier]) }
            catch
            {
                Stop-PSFFunction -String 'Set-AdsOwner.UnresolvedIdentity' -StringValues $Identity -EnableException $EnableException -ErrorRecord $_ -OverrideExceptionMessage
                return
            }
        }
        
        $basePath = 'LDAP://{0}'
        if ($Server) { $basePath = "LDAP://$Server/{0}" }
    }
    process
    {
        if (Test-PSFFunctionInterrupt) { return }
        
        foreach ($pathItem in $Path)
        {
            $aclObject = Get-AdsAcl @adParameters -Path $pathItem
            if ($aclObject.Owner -eq $idReference)
            {
                Write-PSFMessage -String 'Set-AdsOwner.AlreadyOwned' -StringValues $pathItem, $idReference
                continue
            }
            
            # Switching to LDAP as owner changes don't work using AD Module
            if ($Credential) { $directoryEntry = New-Object System.DirectoryServices.DirectoryEntry(($basePath -f $pathItem), $Credential.UserName, $Credential.GetNetworkCredential().Password) }
            else { $directoryEntry = New-Object System.DirectoryServices.DirectoryEntry(($basePath -f $pathItem)) }
            
            Invoke-PSFProtectedCommand -ActionString 'Set-AdsOwner.UpdatingOwner' -ActionStringValues $idReference -ScriptBlock {
                try {
                    $secDescriptor = $directoryEntry.InvokeGet('nTSecurityDescriptor')
                    if (-not $secDescriptor) { throw 'Failed to access security information' }
                    $secDescriptor.Owner = "$idReference"
                    $directoryEntry.InvokeSet('nTSecurityDescriptor', $secDescriptor)
                    $directoryEntry.CommitChanges()
                }
                catch {
                    if (-not $WinRMFailover) { throw }
                    
                    #region Fallback to WinRM
                    $domainController = Get-ADDomainController @adParameters
                    $credParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Credential
                    $ldapPath = "LDAP://localhost/$($pathItem)"
                    
                    Invoke-Command -ComputerName $domainController.HostName @credParam -ScriptBlock {
                        param (
                            $Identity,
                            
                            $LdapPath
                        )
                        try {
                            $directoryEntry = New-Object System.DirectoryServices.DirectoryEntry($LdapPath)
                            $secDescriptor = $directoryEntry.InvokeGet('nTSecurityDescriptor')
                            if (-not $secDescriptor) { throw 'Failed to access security information' }
                            $secDescriptor.Owner = $Identity
                            $directoryEntry.InvokeSet('nTSecurityDescriptor', $secDescriptor)
                            $directoryEntry.CommitChanges()
                        }
                        catch { throw }
                    } -ArgumentList "$idReference", $ldapPath -ErrorAction Stop
                    #endregion Fallback to WinRM
                }
            } -Target $pathItem -EnableException $EnableException.ToBool() -Continue -PSCmdlet $PSCmdlet
        }
    }
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'ADSec' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'ADSec' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'ADSec' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."
Set-PSFConfig -Module 'ADSec' -Name 'WinRM.FailOver' -Value $false -Initialize -Validation 'bool' -Description 'Whether to fail over to WinRM if LDAP-Based operations fail. Used for ownership changes.'

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'ADSec.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "ADSec.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name ADSec.alcohol
#>


New-PSFLicense -Product 'ADSec' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2019-10-01") -Text @"
Copyright (c) 2019 Friedrich Weinmann
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code