UserRightsAssignment.psm1

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

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName UserRightsAssignment.Import.DoDotSource -Fallback $false
if ($UserRightsAssignment_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 UserRightsAssignment.Import.IndividualFiles -Fallback $false
if ($UserRightsAssignment_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
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # 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
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # 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 'UserRightsAssignment' -Language 'en-US'

function Compare-UserRightsAssignment {
    <#
    .SYNOPSIS
        Compare two sets of User Rights Assignments and generate the diff.
     
    .DESCRIPTION
        Compare two sets of User Rights Assignments and generate the diff.
     
    .PARAMETER Assignment
        One set of assignments to compare.
        Provide a list of objects as returned by Get-UserRightsAssignment.
     
    .PARAMETER DiffAssignment
        The other set of assignments to compare.
        Provide a list of objects as returned by Get-UserRightsAssignment.
     
    .EXAMPLE
        PS C:\> Compare-UserRightsAssignment -Assignment $server1 -DiffAssignment $server2
 
        Generate the delta between the two datasets stored in $server1 and $sever2
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [AllowNull()]
        $Assignment,

        [Parameter(Mandatory = $true)]
        [AllowNull()]
        $DiffAssignment
    )

    process {
        $groups = @($Assignment) + @($DiffAssignment) | Group-Object Identifier
        $results = foreach ($group in $groups | Where-Object Count -LT 2) {
            if ($group.Group[0] -in $Assignment) {
                [PSCustomObject]@{
                    ComputerName = $group.Group[0].ComputerName
                    Privilege    = $group.Group[0].Privilege
                    Member       = $group.Group[0].Member
                    Direction    = '=>'
                    Object       = $group.Group[0]
                }
            }
            else {
                [PSCustomObject]@{
                    ComputerName = $group.Group[0].ComputerName
                    Privilege    = $group.Group[0].Privilege
                    Member       = $group.Group[0].Member
                    Direction    = '<='
                    Object       = $group.Group[0]
                }
            }
        }
        $results | Select-PSFObject -KeepInputObject -TypeName 'UserRightsAssignment.Diff' -ShowProperty ComputerName, Direction, Privilege, Member
    }
}


function ConvertTo-UserRightsAssignmentSummary {
    <#
    .SYNOPSIS
        Create a summary result of all user rights assignments.
     
    .DESCRIPTION
        Create a summary result of all user rights assignments.
        Provides a list with one entry per right per computer, grouping all assignees of that right.
     
    .PARAMETER InputObject
        The URA result objects as returned by Get-UserRightsAssignment
     
    .EXAMPLE
        PS C:\> Get-UserRightsAssignment | ConvertTo-UserRightsAssignmentSummary
 
        Generate a per-privilege report of the URA of the local computer.
    #>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        $InputObject
    )

    begin {
        $inputList = [System.Collections.ArrayList]@()

        $selectProps = @(
            @{
                Name       = 'ComputerName'
                Expression = { $_.Group[0].ComputerName }
            }
            @{
                Name       = "Privilege"
                Expression = { $_.Group.Privilege | Sort-Object -Unique }
            }
            @{
                Name       = "Count"
                Expression = { @($_.Group.Member).Count }
            }
            @{
                Name       = "Member"
                Expression = { $_.Group.Member -join "," }
            }
            @{
                Name       = "Entries"
                Expression = { $_.Group }
            }
        )
    }
    process {
        $inputList.AddRange(@($InputObject))
    }
    end {
        $inputList | Group-Object ComputerName, Privilege | Select-PSFObject $selectProps -ShowProperty ComputerName, Privilege, Count, Member -TypeName 'UserRightsAssignment.Summary'
    }
}


function Get-DomainUserRightsAssignment {
    <#
    .SYNOPSIS
        Scan all DCs of a domain for User Rights Assignments.
     
    .DESCRIPTION
        Scan all DCs of a domain for User Rights Assignments.
     
    .PARAMETER Server
        The domain(s) to scan.
     
    .PARAMETER Credential
        The credentials to use.
     
    .EXAMPLE
        PS C:\> Get-DomainUserRightsAssignment
 
        Scan the current user's domain,
 
    .EXAMPLE
        PS C:\> Get-DomainUserRightsAssignment -Server contoso.com
 
        Scan all DCs in the domain contoso.com
    #>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        [PSFComputer[]]
        $Server = $env:USERDNSDOMAIN,

        [PSCredential]
        $Credential
    )

    begin {
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Credential
    }
    process {
        foreach ($serverName in $Server) {
            $parameters.Server = $serverName
            $domain = Get-ADDomain @parameters
            $domainControllers = Get-ADDomainController @parameters -Filter *
            $results = Get-UserRightsAssignment -ComputerName $domainControllers.HostName

            $resultHash = @{ }
            foreach ($group in $results | Group-Object ComputerName) {
                $resultHash[$group.Name] = $group.Group
            }

            [PSCustomObject]@{
                PSTypeName     = 'UserRightsAssignment.DomainInfo'
                Domain         = $domain.DnsRoot
                DomainObject   = $domain
                Entries        = $results
                PoliciesInSync = -not ($results | Group-Object Identifier | Where-Object Count -LT @($domainControllers).Count)
                Summary        = $results | ConvertTo-UserRightsAssignmentSummary
                ByDC           = $resultHash
            }
        }
    }
}


function Get-UserRightsAssignment {
    <#
    .SYNOPSIS
        Execute gpresult on the target computer and get a list of effective user rights assignments.
     
    .DESCRIPTION
        Execute gpresult on the target computer and get a list of effective user rights assignments.
        Uses WinRM for remote access.
     
    .PARAMETER ComputerName
        The computer(s) to scan.
        Servers will be processed in parallel if explicitly bound, sequential if piped.
        Defaults to localohost.
     
    .PARAMETER Credential
        The credentials to use for connecting to the remote host.
 
    .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-UserRightsAssignment
         
        Get the URA of the local host.
    #>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        [PSFComputer[]]
        $ComputerName = $env:COMPUTERNAME,

        [PSCredential]
        $Credential,

        [switch]
        $EnableException
    )

    begin {
        $scriptblock = {
            #region Functions
            function Invoke-SystemCommand {
                <#
                .SYNOPSIS
                    Execute a scriptblock as SYSTEM by setting up a temporary scheduled task.
                 
                .DESCRIPTION
                    Execute a scriptblock as SYSTEM by setting up a temporary scheduled task.
                 
                .PARAMETER Name
                    The name of the task
                 
                .PARAMETER Scriptblock
                    The code to run
                 
                .PARAMETER Mode
                    Whether to run it right away (instant) or after the next reboot (OnBoot).
                    Default: Instant
             
                .PARAMETER Wait
                    Wait for the task to complete.
                    Only applicable in "Instant" mode.
             
                .PARAMETER Timeout
                    Timeout how long we are willing to wait for the task to complete.
                    Only applicable in combination with "-Wait"
                 
                .EXAMPLE
                    PS C:\> Invoke-SystemCommand -Name 'WhoAmI' -ScriptBlock { whoami | Set-Content C:\temp\whoami.txt }
             
                    Executes the scriptblock as system
                #>

                [CmdletBinding()]
                Param (
                    [Parameter(Mandatory = $true)]
                    [string]
                    $Name,
            
                    [Parameter(Mandatory = $true)]
                    [string]
                    $Scriptblock,
            
                    [ValidateSet('Instant', 'OnBoot')]
                    [string]
                    $Mode = 'Instant',
            
                    [switch]
                    $Wait,
            
                    [timespan]
                    $Timeout = '00:00:30'
                )
                
                process {
                    if ($Mode -eq 'OnBoot') { $Scriptblock = "Unregister-ScheduledTask -TaskName 'PowerShell_System_$Name' -Confirm:`$false", $Scriptblock -join "`n`n" }
                    $bytes = [System.Text.Encoding]::Unicode.GetBytes($Scriptblock)
                    $encodedCommand = [Convert]::ToBase64String($bytes)
            
                    $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -EncodedCommand $encodedCommand"
                    $principal = New-ScheduledTaskPrincipal -UserId SYSTEM -RunLevel Highest -LogonType Password
                    switch ($Mode) {
                        'Instant' { $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) }
                        'OnBoot' { $trigger = New-ScheduledTaskTrigger -AtStartup }
                    }
                    $task = Register-ScheduledTask -TaskName "PowerShell_System_$Name" -Description "PowerShell Task - $Name" -Action $action -Trigger $trigger -Principal $principal
                    if ($Mode -eq 'Instant') {
                        $task | Start-ScheduledTask
                        if (-not $Wait) {
                            Start-Sleep -Seconds 1
                        }
                        else {
                            $limit = (Get-Date).Add($Timeout)
                            while (($task | Get-ScheduledTask).State -ne "Ready") {
                                if ($limit -lt (Get-Date)) {
                                    $task | Unregister-ScheduledTask -Confirm:$false
                                    throw "Task execution exceeded time limit ($Timeout)"
                                }
                            }
                        }
                        $task | Unregister-ScheduledTask -Confirm:$false
                    }
                }
            }
            #endregion Function
            $csDomain = (Get-ComputerInfo -Property CsDomain).CsDomain
            
            $result = [PSCustomObject]@{
                ComputerName   = $ENV:COMPUTERNAME
                ComputerDomain = $csDomain
                ComputerFqdn   = "$($ENV:COMPUTERNAME).$($csDomain)"
                Success        = $false
                Results        = @()
                Message        = [System.Collections.ArrayList]::new()
            }
            try {
                Invoke-SystemCommand -Name 'GPReport' -ScriptBlock {
                    gpresult /F /SCOPE COMPUTER /X C:\GPReport.xml
                } -Wait
            }
            catch {
                $null = $result.Message.Add("$_")
                Write-Warning "[$($ENV:COMPUTERNAME).$($csDomain)] $_"
            }

            if (-not (Test-Path 'C:\GPReport.xml')) {
                $null = $result.Message.Add("GPReport.xml not found")
                return $result
            }

            try { [xml]$xml = Get-Content C:\GPReport.xml -ErrorAction Stop }
            catch {
                Write-Warning "[$($ENV:COMPUTERNAME).$($csDomain)] Error Reading temporary GP Report File: $_"
                Remove-Item -Path C:\GPReport.xml -Force -ErrorAction Ignore
                $null = $result.Message.Add("Error Reading temporary GP Report File: $_")
                return $result
            }
            Remove-Item -Path C:\GPReport.xml -Force -ErrorAction Ignore
            

            $assignments = @($xml.Rsop.ComputerResults.ExtensionData).Where{
                $_.Name.'#text' -eq 'Security'
            }.Extension.UserRightsAssignment

            $gpoCache = @{ }

            $result.Results = foreach ($assignment in $assignments) {
                if (-not $gpoCache[$assignment.GPO.Identifier.'#text']) {
                    $gpoCache[$assignment.GPO.Identifier.'#text'] = Get-GPO -Guid $assignment.GPO.Identifier.'#text' -Server localhost
                }
                
                foreach ($member in $assignment.Member) {
                    [PSCustomObject]@{
                        ComputerName   = $ENV:COMPUTERNAME
                        ComputerDomain = $csDomain
                        ComputerFqdn   = "$($ENV:COMPUTERNAME).$($csDomain)"
                        Privilege      = $assignment.Name
                        GPOId          = $assignment.GPO.Identifier.'#text'
                        GPOName        = $gpoCache[$assignment.GPO.Identifier.'#text'].DisplayName
                        Member         = $member.Name.'#text'
                        Identifier     = "$($assignment.Name)|$($member.Name.'#text')"
                    }
                }
            }
            $result.Success = $true
            $result
        }
    }
    process {
        $failed = $null
        $results = Invoke-PSFCommand -ComputerName $ComputerName -Credential $Credential -ScriptBlock $scriptblock -ErrorVariable failed -ErrorAction SilentlyContinue
        $failedProcessed = $failed | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] } | Group-Object {
            $_.Exception.Message
        } | ForEach-Object { $_.Group[0] }
        foreach ($errorItem in $failedProcessed) {
            Write-PSFMessage -Level Warning -Message "[$($errorItem.TargetObject.OriginalConnectionInfo.ComputerName)]" -ErrorRecord $errorItem -Tag error, WinRM -PSCmdlet $PSCmdlet -EnableException $EnableException.ToBool() -Target $errorItem.TargetObject.OriginalConnectionInfo.ComputerName
        }
        $resultData = foreach ($result in $results) {
            if ($result.Success) {
                $result.Results
                continue
            }

            Write-PSFMessage -Level Warning -Message "[$($result.ComputerFqdn)] Error gathering data:`n`t{0}" -StringValues ($result.Message -join "`n`t") -Target $result.ComputerFqdn -Tag error, processing -PSCmdlet $PSCmdlet -EnableException $EnableException.ToBool()
        }
        # Store and return values, in order to avoid mixing output with warnings
        $resultData
    }
}


function Import-UserRightsAssignment {
    <#
    .SYNOPSIS
        Reads a GP Results XML file and processes any applicable UserRightsAssignments.
     
    .DESCRIPTION
        Reads a GP Results XML file and processes any applicable UserRightsAssignments.
 
        To generate such a file, use the following line on the system you want to generate the report:
        gpresult /F /SCOPE COMPUTER /X GPReport.xml
     
    .PARAMETER Path
        Path to the file(s) containing gp result XML files.
     
    .EXAMPLE
        PS C:\> Get-ChildItem *.xml | Import-UserRightsAssignment
 
        Reads the User Rights Assignment settings from all XML files in the current folder.
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingEmptyCatchBlock', '')]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('FullName')]
        [string[]]
        $Path
    )
    process {
        foreach ($pathItem in $Path) {
            try { [xml]$xml = Get-Content -Path $pathItem -ErrorAction Stop }
            catch {
                Write-PSFMessage -Level Error -Message "Error reading XML file: $pathItem" -ErrorRecord $_ -PSCmdlet $PSCmdlet -EnableException $true
                continue
            }

            $computerDomain = $xml.Rsop.ComputerResults.Domain
            $computerName = $xml.Rsop.ComputerResults.Name -replace '^.*?\\' -replace '\$$'
            
            $assignments = @($xml.Rsop.ComputerResults.ExtensionData).Where{
                $_.Name.'#text' -eq 'Security'
            }.Extension.UserRightsAssignment

            $gpoCache = @{ }

            foreach ($assignment in $assignments) {
                if (-not $gpoCache[$assignment.GPO.Identifier.'#text']) {
                    try { $gpoCache[$assignment.GPO.Identifier.'#text'] = Get-ADObject -LdapFilter "(&(objectClass=groupPolicyContainer)(name={$([guid]$assignment.GPO.Identifier.'#text')}))" -Properties DisplayName -Server $computerDomain -ErrorAction Ignore }
                    catch { } # Do nothing - if we can't resolve it, we can't resolve it.
                }
                
                foreach ($member in $assignment.Member) {
                    [PSCustomObject]@{
                        ComputerName   = $computerName
                        ComputerDomain = $computerDomain
                        ComputerFqdn   = "$($computerName).$($computerDomain)"
                        Privilege      = $assignment.Name
                        GPOId          = $assignment.GPO.Identifier.'#text'
                        GPOName        = $gpoCache[$assignment.GPO.Identifier.'#text'].DisplayName
                        Member         = $member.Name.'#text'
                        Identifier     = "$($assignment.Name)|$($member.Name.'#text')"
                    }
                }
            }
        }
    }
}


<#
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 'UserRightsAssignment' -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 'UserRightsAssignment' -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 'UserRightsAssignment' -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."

<#
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 'UserRightsAssignment.ScriptBlockName' -Scriptblock {
     
}
#>


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


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


New-PSFLicense -Product 'UserRightsAssignment' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2021-06-03") -Text @"
Copyright (c) 2021 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