From 2a140fa75113accbc21b6c4c04696e9f8e0550ba Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:03:38 -0800 Subject: [PATCH] refactor(helpers): move the helpers of three analyzer rules out The fourth part of #65. Six functions nested in Find-IslInteractiveCall, Find-IslExitCodeIssue and Find-IslModuleDependency are private functions in files of their own, advanced functions with full help and output types, cut from the rules with their bodies unchanged: - Get-CredentialArgument -> Get-IslCredentialArgument - Get-CredentialSource -> Get-IslCredentialSource - Get-VariableCredentialSource -> Get-IslVariableCredentialSource, with the script's tree as -Ast - Get-ReturnReplacement -> Get-IslReturnReplacement - Test-ExitFollowsReturn -> Test-IslExitFollowsReturn - Test-InBox -> Test-IslInboxModuleName, with the list as -InboxModule Write-Missing built a finding, and Build-RuleReference.ps1 reads the finding tables from the rule files only, so it stays in the rule as a loop over the modules the rule collected. docs/Rules.md regenerates unchanged. Each new function has a test file of its own; the rules' tests are unchanged. Refs #65. --- CHANGELOG.md | 3 +- Private/Get-IslCredentialArgument.ps1 | 52 ++++++++ Private/Get-IslCredentialSource.ps1 | 79 ++++++++++++ Private/Get-IslReturnReplacement.ps1 | 33 +++++ Private/Get-IslVariableCredentialSource.ps1 | 72 +++++++++++ Private/Rules/Find-IslExitCodeIssue.ps1 | 27 +--- Private/Rules/Find-IslInteractiveCall.ps1 | 118 +----------------- Private/Rules/Find-IslModuleDependency.ps1 | 60 +++++---- Private/Test-IslExitFollowsReturn.ps1 | 39 ++++++ Private/Test-IslInboxModuleName.ps1 | 46 +++++++ .../Get-IslCredentialArgument.Tests.ps1 | 52 ++++++++ .../Private/Get-IslCredentialSource.Tests.ps1 | 65 ++++++++++ .../Get-IslReturnReplacement.Tests.ps1 | 39 ++++++ .../Get-IslVariableCredentialSource.Tests.ps1 | 60 +++++++++ .../Test-IslExitFollowsReturn.Tests.ps1 | 41 ++++++ .../Private/Test-IslInboxModuleName.Tests.ps1 | 40 ++++++ 16 files changed, 656 insertions(+), 170 deletions(-) create mode 100644 Private/Get-IslCredentialArgument.ps1 create mode 100644 Private/Get-IslCredentialSource.ps1 create mode 100644 Private/Get-IslReturnReplacement.ps1 create mode 100644 Private/Get-IslVariableCredentialSource.ps1 create mode 100644 Private/Test-IslExitFollowsReturn.ps1 create mode 100644 Private/Test-IslInboxModuleName.ps1 create mode 100644 Tests/Unit/Private/Get-IslCredentialArgument.Tests.ps1 create mode 100644 Tests/Unit/Private/Get-IslCredentialSource.Tests.ps1 create mode 100644 Tests/Unit/Private/Get-IslReturnReplacement.Tests.ps1 create mode 100644 Tests/Unit/Private/Get-IslVariableCredentialSource.Tests.ps1 create mode 100644 Tests/Unit/Private/Test-IslExitFollowsReturn.Tests.ps1 create mode 100644 Tests/Unit/Private/Test-IslInboxModuleName.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 9961ab7..05d529c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,7 +44,8 @@ entries are carried over from the manifest's release notes. - The helper functions nested in `Test-IntuneScript`, `Test-IntuneWin32Requirement`, `Test-IntuneAssignmentFilter`, `Export-IntuneFindingSarif`, `Export-IntuneAgentDiagnostic`, - `Get-IslSetting`, `Get-IslAgentLogEvent` and `Invoke-IslGraphRequest` are private functions of their own, each an + `Get-IslSetting`, `Get-IslAgentLogEvent`, `Invoke-IslGraphRequest` and three analyzer rules + (`IslInteractiveCall`, `IslExitCodeIssue`, `IslModuleDependency`) are private functions of their own, each an advanced function with help and tests (#65). Nothing changes for a caller, except that the error of a settings value that is not allowed now names `ConvertTo-IslSettingsObject` after `SettingsInvalid` in its `FullyQualifiedErrorId`. diff --git a/Private/Get-IslCredentialArgument.ps1 b/Private/Get-IslCredentialArgument.ps1 new file mode 100644 index 0000000..adc9e4a --- /dev/null +++ b/Private/Get-IslCredentialArgument.ps1 @@ -0,0 +1,52 @@ +function Get-IslCredentialArgument { + <# + .SYNOPSIS + Gets what a Get-Credential call is handed as its credential. + + .DESCRIPTION + For the interactive-call rule: Get-Credential -Credential returns a credential that is already + built, and prompts only for the password of a user name. This gives the argument of + -Credential, named by any prefix of the name, or the first positional argument, which binds to + -Credential. It gives nothing when the call names -Message, -UserName or -Title, which always + prompt, or has no such argument. A value right after another parameter belongs to that + parameter and is passed over. + + .PARAMETER Command + The Get-Credential call. + + .EXAMPLE + Get-IslCredentialArgument -Command $command + + The syntax tree of $credential for Get-Credential -Credential $credential. + + .INPUTS + None. + + .OUTPUTS + System.Management.Automation.Language.Ast. The argument, or nothing. + #> + [CmdletBinding()] + [OutputType([System.Management.Automation.Language.Ast])] + param( + [Parameter(Mandatory)] + [System.Management.Automation.Language.CommandAst]$Command + ) + + foreach ($prompting in 'Message', 'UserName', 'Title') { + if (Test-IslCommandParameter -Command $Command -ParameterName $prompting) { return } + } + $elements = @($Command.CommandElements | Select-Object -Skip 1) + for ($index = 0; $index -lt $elements.Count; $index++) { + $element = $elements[$index] + if ($element.GetType().Name -eq 'CommandParameterAst') { + if (-not 'Credential'.StartsWith($element.ParameterName, 'OrdinalIgnoreCase')) { continue } + if ($element.Argument) { return $element.Argument } + if ($index + 1 -lt $elements.Count) { return $elements[$index + 1] } + return + } + # A value right after another parameter belongs to that parameter + $previous = if ($index -gt 0) { $elements[$index - 1] } else { $null } + $taken = $previous -and $previous.GetType().Name -eq 'CommandParameterAst' -and -not $previous.Argument + if (-not $taken) { return $element } + } +} diff --git a/Private/Get-IslCredentialSource.ps1 b/Private/Get-IslCredentialSource.ps1 new file mode 100644 index 0000000..29df8ab --- /dev/null +++ b/Private/Get-IslCredentialSource.ps1 @@ -0,0 +1,79 @@ +function Get-IslCredentialSource { + <# + .SYNOPSIS + Tells how an expression builds a credential, when it can only ever produce one. + + .DESCRIPTION + For the interactive-call rule. The expression is recognised when it is the PSCredential + constructor, New-Object with the PSCredential type, a [pscredential] cast, or Import-Clixml, + which hands back a credential that Export-Clixml wrote. Parentheses, a pipeline of one element + and an expression statement around it are looked through. Anything else, a member or another + call included, gives nothing. + + .PARAMETER Expression + The syntax tree of the expression. + + .EXAMPLE + Get-IslCredentialSource -Expression $assignment.Right + + '[pscredential]::new()' for $credential = [pscredential]::new($user, $secure). + + .INPUTS + None. + + .OUTPUTS + System.String. How the credential is built, or nothing. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [AllowNull()] + [System.Management.Automation.Language.Ast]$Expression + ) + + $credentialType = '^(System\.Management\.Automation\.)?PSCredential$' + # Parentheses, a one-element pipeline and the expression statement around a value are wrappers + $unwrapped = $false + while ($Expression -and -not $unwrapped) { + $kind = $Expression.GetType().Name + if ($kind -eq 'ParenExpressionAst') { $Expression = $Expression.Pipeline } + elseif ($kind -eq 'PipelineAst' -and @($Expression.PipelineElements).Count -eq 1) { + $Expression = $Expression.PipelineElements[0] + } + elseif ($kind -eq 'CommandExpressionAst') { $Expression = $Expression.Expression } + else { $unwrapped = $true } + } + if (-not $Expression) { return } + switch ($Expression.GetType().Name) { + 'CommandAst' { + $commandName = $Expression.GetCommandName() + if ($commandName -eq 'Import-Clixml') { return 'Import-Clixml' } + if ($commandName -ne 'New-Object') { return } + $typeName = $null + $elements = @($Expression.CommandElements | Select-Object -Skip 1) + for ($index = 0; $index -lt $elements.Count; $index++) { + $element = $elements[$index] + if ($element.GetType().Name -eq 'CommandParameterAst') { + if (-not 'TypeName'.StartsWith($element.ParameterName, 'OrdinalIgnoreCase')) { continue } + if ($element.Argument) { $typeName = $element.Argument.Extent.Text } + elseif ($index + 1 -lt $elements.Count) { $typeName = $elements[$index + 1].Extent.Text } + break + } + $previous = if ($index -gt 0) { $elements[$index - 1] } else { $null } + $taken = $previous -and $previous.GetType().Name -eq 'CommandParameterAst' -and + -not $previous.Argument + if (-not $taken) { $typeName = $element.Extent.Text; break } + } + if ("$typeName".Trim('''"') -match $credentialType) { return 'New-Object PSCredential' } + } + 'InvokeMemberExpressionAst' { + $onType = $Expression.Expression.GetType().Name -eq 'TypeExpressionAst' -and + $Expression.Expression.TypeName.FullName -match $credentialType + if ($onType -and "$($Expression.Member.Value)" -eq 'new') { return '[pscredential]::new()' } + } + 'ConvertExpressionAst' { + if ($Expression.Type.TypeName.FullName -match $credentialType) { return 'a [pscredential] cast' } + } + } +} diff --git a/Private/Get-IslReturnReplacement.ps1 b/Private/Get-IslReturnReplacement.ps1 new file mode 100644 index 0000000..5f458a4 --- /dev/null +++ b/Private/Get-IslReturnReplacement.ps1 @@ -0,0 +1,33 @@ +function Get-IslReturnReplacement { + <# + .SYNOPSIS + Gets the edit that says what a return at script scope already does. + + .DESCRIPTION + For the exit-code rule. A return at script scope ends the script with exit code 0, after it + has written the value it returned. The edit writes that out: the value followed by exit 0, or + exit 0 alone for a bare return. + + .PARAMETER Return + The return statement. + + .EXAMPLE + Get-IslReturnReplacement -Return $return + + '1; exit 0' for return 1. + + .INPUTS + None. + + .OUTPUTS + System.String. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [System.Management.Automation.Language.ReturnStatementAst]$Return + ) + + if ($Return.Pipeline) { "$($Return.Pipeline.Extent.Text); exit 0" } else { 'exit 0' } +} diff --git a/Private/Get-IslVariableCredentialSource.ps1 b/Private/Get-IslVariableCredentialSource.ps1 new file mode 100644 index 0000000..043138c --- /dev/null +++ b/Private/Get-IslVariableCredentialSource.ps1 @@ -0,0 +1,72 @@ +function Get-IslVariableCredentialSource { + <# + .SYNOPSIS + Tells how a variable comes to hold a credential, when every value the script gives it is one. + + .DESCRIPTION + For the interactive-call rule. Every assignment to the variable anywhere in the script, with + or without a scope prefix, must build a credential as Get-IslCredentialSource recognises it or + be typed [pscredential], and a parameter of that name must be typed [pscredential]. The result + names each distinct way, joined by commas. When the script never gives the variable a value, + or any one of its values could be something else, the function gives nothing. + + .PARAMETER Variable + The variable, as it is used in the call. + + .PARAMETER Ast + The syntax tree of the whole script, where the assignments and parameters are looked for. + + .EXAMPLE + Get-IslVariableCredentialSource -Variable $handed -Ast $Context.Ast + + 'Import-Clixml' for a $credential that the script assigns only from Import-Clixml. + + .INPUTS + None. + + .OUTPUTS + System.String. How the credential is built, or nothing. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [System.Management.Automation.Language.VariableExpressionAst]$Variable, + + [Parameter(Mandatory)] + [System.Management.Automation.Language.Ast]$Ast + ) + + $credentialType = '^(System\.Management\.Automation\.)?PSCredential$' + $scopePrefix = '^(script|local|private|global):' + $variableName = $Variable.VariablePath.UserPath -replace $scopePrefix, '' + $sources = [System.Collections.Generic.List[string]]::new() + $assignments = Find-IslAstNode -Ast $Ast -TypeName AssignmentStatementAst -Where { + param($node) + $target = $node.Left + $wrapped = $target.GetType().Name -in 'ConvertExpressionAst', 'AttributedExpressionAst' + if ($wrapped) { $target = $target.Child } + $target.GetType().Name -eq 'VariableExpressionAst' -and + ($target.VariablePath.UserPath -replace $scopePrefix, '') -eq $variableName + } + foreach ($assignment in $assignments) { + $typed = $assignment.Left.GetType().Name -eq 'ConvertExpressionAst' -and + $assignment.Left.Type.TypeName.FullName -match $credentialType + $source = if ($typed) { 'a [pscredential] variable' } + else { Get-IslCredentialSource -Expression $assignment.Right } + if (-not $source) { return } + $sources.Add($source) + } + $parameters = Find-IslAstNode -Ast $Ast -TypeName ParameterAst -Where { + param($node) + $node.Name.VariablePath.UserPath -eq $variableName + } + foreach ($parameter in $parameters) { + $typed = @($parameter.Attributes | Where-Object { + $_.GetType().Name -eq 'TypeConstraintAst' -and $_.TypeName.FullName -match $credentialType + }).Count -gt 0 + if (-not $typed) { return } + $sources.Add('a [pscredential] parameter') + } + if ($sources.Count) { @($sources | Select-Object -Unique) -join ', ' } +} diff --git a/Private/Rules/Find-IslExitCodeIssue.ps1 b/Private/Rules/Find-IslExitCodeIssue.ps1 index 92d310c..dac1e9a 100644 --- a/Private/Rules/Find-IslExitCodeIssue.ps1 +++ b/Private/Rules/Find-IslExitCodeIssue.ps1 @@ -29,25 +29,6 @@ function Find-IslExitCodeIssue { $rule = 'IslExitCodeIssue' $type = $Context.ScriptType - # The edit that says what a script-scope return already does: exit 0, after any value it returned - function Get-ReturnReplacement { - param($Return) - if ($Return.Pipeline) { "$($Return.Pipeline.Extent.Text); exit 0" } else { 'exit 0' } - } - - # An exit other than 0 after the return in the same block is the exit the author meant. Writing - # 'exit 0' in front of it would leave it unreachable with no finding left to say so, so that - # return gets no edit and stays reported - function Test-ExitFollowsReturn { - param($Return) - $passed = $false - foreach ($statement in @($Return.Parent.Statements)) { - if ($statement -eq $Return) { $passed = $true; continue } - if (-not $passed -or $statement.GetType().Name -ne 'ExitStatementAst') { continue } - if ($statement.Pipeline -and $statement.Pipeline.Extent.Text.Trim() -ne '0') { return $true } - } - $false - } if ($type -notin 'Detection', 'Remediation', 'Win32Detection') { return } $ast = $Context.Ast @@ -86,8 +67,8 @@ function Find-IslExitCodeIssue { Evidence = ('"return 1; exit 1" ran with exit code 0 and the remediation was skipped; ' + 'Microsoft''s sample detection scripts use this pattern (REM-RETURN-EXIT)') } - if (-not (Test-ExitFollowsReturn -Return $return)) { - $findingSplat.Fix = @{ Replacement = Get-ReturnReplacement -Return $return } + if (-not (Test-IslExitFollowsReturn -Return $return)) { + $findingSplat.Fix = @{ Replacement = Get-IslReturnReplacement -Return $return } } New-IslFinding @findingSplat } @@ -164,8 +145,8 @@ function Find-IslExitCodeIssue { 'what was actually done') Evidence = 'Script-scope return produced exit code 0 (REM-RETURN-EXIT)' } - if (-not (Test-ExitFollowsReturn -Return $return)) { - $findingSplat.Fix = @{ Replacement = Get-ReturnReplacement -Return $return } + if (-not (Test-IslExitFollowsReturn -Return $return)) { + $findingSplat.Fix = @{ Replacement = Get-IslReturnReplacement -Return $return } } New-IslFinding @findingSplat } diff --git a/Private/Rules/Find-IslInteractiveCall.ps1 b/Private/Rules/Find-IslInteractiveCall.ps1 index 6e84b55..30849fc 100644 --- a/Private/Rules/Find-IslInteractiveCall.ps1 +++ b/Private/Rules/Find-IslInteractiveCall.ps1 @@ -33,118 +33,6 @@ function Find-IslInteractiveCall { 'in 12 ms under the agent, without a prompt (REM-CRED-BUILT)') $ast = $Context.Ast - # What Get-Credential is handed as -Credential, by name or as the first positional argument. - # Nothing when it is called bare or with -Message, -UserName or -Title, which always prompt - function Get-CredentialArgument { - param($Command) - foreach ($prompting in 'Message', 'UserName', 'Title') { - if (Test-IslCommandParameter -Command $Command -ParameterName $prompting) { return } - } - $elements = @($Command.CommandElements | Select-Object -Skip 1) - for ($index = 0; $index -lt $elements.Count; $index++) { - $element = $elements[$index] - if ($element.GetType().Name -eq 'CommandParameterAst') { - if (-not 'Credential'.StartsWith($element.ParameterName, 'OrdinalIgnoreCase')) { continue } - if ($element.Argument) { return $element.Argument } - if ($index + 1 -lt $elements.Count) { return $elements[$index + 1] } - return - } - # A value right after another parameter belongs to that parameter - $previous = if ($index -gt 0) { $elements[$index - 1] } else { $null } - $taken = $previous -and $previous.GetType().Name -eq 'CommandParameterAst' -and -not $previous.Argument - if (-not $taken) { return $element } - } - } - - $credentialType = '^(System\.Management\.Automation\.)?PSCredential$' - - # How an expression builds a credential, when it can only ever produce one: the constructor, - # New-Object with the type, a cast, or Import-Clixml, which hands back a credential that - # Export-Clixml wrote. Nothing for anything else, a member or a call included - function Get-CredentialSource { - param($Expression) - # Parentheses, a one-element pipeline and the expression statement around a value are wrappers - $unwrapped = $false - while ($Expression -and -not $unwrapped) { - $kind = $Expression.GetType().Name - if ($kind -eq 'ParenExpressionAst') { $Expression = $Expression.Pipeline } - elseif ($kind -eq 'PipelineAst' -and @($Expression.PipelineElements).Count -eq 1) { - $Expression = $Expression.PipelineElements[0] - } - elseif ($kind -eq 'CommandExpressionAst') { $Expression = $Expression.Expression } - else { $unwrapped = $true } - } - if (-not $Expression) { return } - switch ($Expression.GetType().Name) { - 'CommandAst' { - $commandName = $Expression.GetCommandName() - if ($commandName -eq 'Import-Clixml') { return 'Import-Clixml' } - if ($commandName -ne 'New-Object') { return } - $typeName = $null - $elements = @($Expression.CommandElements | Select-Object -Skip 1) - for ($index = 0; $index -lt $elements.Count; $index++) { - $element = $elements[$index] - if ($element.GetType().Name -eq 'CommandParameterAst') { - if (-not 'TypeName'.StartsWith($element.ParameterName, 'OrdinalIgnoreCase')) { continue } - if ($element.Argument) { $typeName = $element.Argument.Extent.Text } - elseif ($index + 1 -lt $elements.Count) { $typeName = $elements[$index + 1].Extent.Text } - break - } - $previous = if ($index -gt 0) { $elements[$index - 1] } else { $null } - $taken = $previous -and $previous.GetType().Name -eq 'CommandParameterAst' -and - -not $previous.Argument - if (-not $taken) { $typeName = $element.Extent.Text; break } - } - if ("$typeName".Trim('''"') -match $credentialType) { return 'New-Object PSCredential' } - } - 'InvokeMemberExpressionAst' { - $onType = $Expression.Expression.GetType().Name -eq 'TypeExpressionAst' -and - $Expression.Expression.TypeName.FullName -match $credentialType - if ($onType -and "$($Expression.Member.Value)" -eq 'new') { return '[pscredential]::new()' } - } - 'ConvertExpressionAst' { - if ($Expression.Type.TypeName.FullName -match $credentialType) { return 'a [pscredential] cast' } - } - } - } - - # How a variable comes to hold a credential, when every place the script gives it a value - # builds one: its assignments, and a parameter typed [pscredential]. Nothing when the script - # never gives it a value, or any one of them could be something else - function Get-VariableCredentialSource { - param($Variable) - $scopePrefix = '^(script|local|private|global):' - $variableName = $Variable.VariablePath.UserPath -replace $scopePrefix, '' - $sources = [System.Collections.Generic.List[string]]::new() - $assignments = Find-IslAstNode -Ast $ast -TypeName AssignmentStatementAst -Where { - param($node) - $target = $node.Left - $wrapped = $target.GetType().Name -in 'ConvertExpressionAst', 'AttributedExpressionAst' - if ($wrapped) { $target = $target.Child } - $target.GetType().Name -eq 'VariableExpressionAst' -and - ($target.VariablePath.UserPath -replace $scopePrefix, '') -eq $variableName - } - foreach ($assignment in $assignments) { - $typed = $assignment.Left.GetType().Name -eq 'ConvertExpressionAst' -and - $assignment.Left.Type.TypeName.FullName -match $credentialType - $source = if ($typed) { 'a [pscredential] variable' } - else { Get-CredentialSource -Expression $assignment.Right } - if (-not $source) { return } - $sources.Add($source) - } - $parameters = Find-IslAstNode -Ast $ast -TypeName ParameterAst -Where { - param($node) - $node.Name.VariablePath.UserPath -eq $variableName - } - foreach ($parameter in $parameters) { - $typed = @($parameter.Attributes | Where-Object { - $_.GetType().Name -eq 'TypeConstraintAst' -and $_.TypeName.FullName -match $credentialType - }).Count -gt 0 - if (-not $typed) { return } - $sources.Add('a [pscredential] parameter') - } - if ($sources.Count) { @($sources | Select-Object -Unique) -join ', ' } - } $alwaysPrompt = 'Read-Host', 'Pause', 'Out-GridView', 'Show-Command', 'Get-Credential' foreach ($command in (Find-IslCommand -Ast $ast -Name $alwaysPrompt)) { @@ -152,12 +40,12 @@ function Find-IslInteractiveCall { # Get-Credential -Credential returns a credential that is already built and prompts for the # password of a user name. A literal is a name; an expression or variable that can only # hold a credential never prompts; anything else cannot be told apart here - $handed = if ($name -eq 'Get-Credential') { Get-CredentialArgument -Command $command } + $handed = if ($name -eq 'Get-Credential') { Get-IslCredentialArgument -Command $command } $literalTypes = 'StringConstantExpressionAst', 'ExpandableStringExpressionAst' $source = if ($handed -and $handed.GetType().Name -eq 'VariableExpressionAst') { - Get-VariableCredentialSource -Variable $handed + Get-IslVariableCredentialSource -Variable $handed -Ast $ast } - elseif ($handed) { Get-CredentialSource -Expression $handed } + elseif ($handed) { Get-IslCredentialSource -Expression $handed } if ($source) { $findingSplat = @{ RuleName = $rule diff --git a/Private/Rules/Find-IslModuleDependency.ps1 b/Private/Rules/Find-IslModuleDependency.ps1 index 6b629ca..0cc19ce 100644 --- a/Private/Rules/Find-IslModuleDependency.ps1 +++ b/Private/Rules/Find-IslModuleDependency.ps1 @@ -37,32 +37,8 @@ function Find-IslModuleDependency { 'killed at the 60-minute timeout (detectionState scriptError) while every remediation queued behind ' + 'it waited (REM-INSTALL-MODULE)') - function Test-InBox { - param([string]$Name) - # A path is a file the script ships or references, not a module by name; leave it to the - # relative-path rule - if ($Name -match '[\\/]' -or $Name -match '\.psm?1$|\.psd1$') { return $true } - if ($Name -match '[\*\?\$]') { return $true } - $Name -in $inbox - } - - function Write-Missing { - param([string]$Name, $Extent, [string]$How) - $findingSplat = @{ - RuleName = $rule - Severity = 'Warning' - Context = $Context - Extent = $Extent - Message = ("$How names $Name, which is not in-box under the agent's SYSTEM session. It must be " + - 'installed machine-wide (Program Files\WindowsPowerShell\Modules) before the script runs; a ' + - '#Requires for a missing module stops the script before it starts (exit 1, ' + - 'ScriptRequiresMissingModules) and a detection failing that way still runs the remediation') - Evidence = $pathEvidence + '; a #Requires -Modules for a module the device lacks exited 1 without ' + - 'running, the remediation ran anyway, and Graph reported detectionState fail, remediationState ' + - 'remediationFailed (REM-REQUIRES-MODULE)' - } - New-IslFinding @findingSplat - } + # Each module named that is not in-box: what names it, and where + $missing = [System.Collections.Generic.List[hashtable]]::new() # A script without a #Requires line has no requirements object at all $requirements = $Context.Ast.ScriptRequirements @@ -71,15 +47,17 @@ function Find-IslModuleDependency { $requiredModules = @($requirements.RequiredModules | Where-Object { $_ }) } foreach ($required in $requiredModules) { - if (-not (Test-InBox -Name "$($required.Name)")) { - Write-Missing -Name $required.Name -Extent $Context.Ast.Extent -How '#Requires -Modules' + if (-not (Test-IslInboxModuleName -InboxModule $inbox -Name "$($required.Name)")) { + $missing.Add(@{ Name = $required.Name; Extent = $Context.Ast.Extent; How = '#Requires -Modules' }) } } foreach ($using in (Find-IslAstNode -Ast $Context.Ast -TypeName UsingStatementAst -Where { param($node) "$($node.UsingStatementKind)" -eq 'Module' })) { $name = if ($using.Name) { $using.Name.Value } else { "$($using.ModuleSpecification.Extent.Text)" } - if (-not (Test-InBox -Name $name)) { Write-Missing -Name $name -Extent $using.Extent -How 'using module' } + if (-not (Test-IslInboxModuleName -InboxModule $inbox -Name $name)) { + $missing.Add(@{ Name = $name; Extent = $using.Extent; How = 'using module' }) + } } foreach ($command in (Find-IslCommand -Ast $Context.Ast -Name 'Import-Module', 'ipmo')) { $elements = $command.CommandElements @@ -100,13 +78,33 @@ function Find-IslModuleDependency { else { @($nameElement) } foreach ($literal in $literals) { if ($literal.GetType().Name -ne 'StringConstantExpressionAst') { continue } - if (-not (Test-InBox -Name $literal.Value)) { - Write-Missing -Name $literal.Value -Extent $command.Extent -How 'Import-Module' + if (-not (Test-IslInboxModuleName -InboxModule $inbox -Name $literal.Value)) { + $missing.Add(@{ Name = $literal.Value; Extent = $command.Extent; How = 'Import-Module' }) } } } } + foreach ($entry in $missing) { + $name = $entry['Name'] + $how = $entry['How'] + $extent = $entry['Extent'] + $findingSplat = @{ + RuleName = $rule + Severity = 'Warning' + Context = $Context + Extent = $extent + Message = ("$How names $Name, which is not in-box under the agent's SYSTEM session. It must be " + + 'installed machine-wide (Program Files\WindowsPowerShell\Modules) before the script runs; a ' + + '#Requires for a missing module stops the script before it starts (exit 1, ' + + 'ScriptRequiresMissingModules) and a detection failing that way still runs the remediation') + Evidence = $pathEvidence + '; a #Requires -Modules for a module the device lacks exited 1 without ' + + 'running, the remediation ran anyway, and Graph reported detectionState fail, remediationState ' + + 'remediationFailed (REM-REQUIRES-MODULE)' + } + New-IslFinding @findingSplat + } + $installers = 'Install-Module', 'Install-PSResource', 'Install-Package', 'Save-Module', 'Update-Module' foreach ($command in (Find-IslCommand -Ast $Context.Ast -Name $installers)) { $findingSplat = @{ diff --git a/Private/Test-IslExitFollowsReturn.ps1 b/Private/Test-IslExitFollowsReturn.ps1 new file mode 100644 index 0000000..c312af0 --- /dev/null +++ b/Private/Test-IslExitFollowsReturn.ps1 @@ -0,0 +1,39 @@ +function Test-IslExitFollowsReturn { + <# + .SYNOPSIS + Tells whether an exit with a code other than 0 follows a return in the same block. + + .DESCRIPTION + For the exit-code rule. Such an exit is the one the author meant. Writing exit 0 in front of + it would leave it unreachable with no finding left to say so, so a return that it follows gets + no edit and stays reported. + + .PARAMETER Return + The return statement. + + .EXAMPLE + Test-IslExitFollowsReturn -Return $return + + $true for the return in: return 'missing'; exit 1. + + .INPUTS + None. + + .OUTPUTS + System.Boolean. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [System.Management.Automation.Language.ReturnStatementAst]$Return + ) + + $passed = $false + foreach ($statement in @($Return.Parent.Statements)) { + if ($statement -eq $Return) { $passed = $true; continue } + if (-not $passed -or $statement.GetType().Name -ne 'ExitStatementAst') { continue } + if ($statement.Pipeline -and $statement.Pipeline.Extent.Text.Trim() -ne '0') { return $true } + } + $false +} diff --git a/Private/Test-IslInboxModuleName.ps1 b/Private/Test-IslInboxModuleName.ps1 new file mode 100644 index 0000000..c9df60e --- /dev/null +++ b/Private/Test-IslInboxModuleName.ps1 @@ -0,0 +1,46 @@ +function Test-IslInboxModuleName { + <# + .SYNOPSIS + Tells whether a module name that a script uses is one the agent's SYSTEM session has. + + .DESCRIPTION + For the module-dependency rule. A name is in-box when it is in the list of modules that come + with Windows (Get-IslInboxModule). A path, a name that ends in .psm1, .ps1 or .psd1, and a name + with a wildcard or a variable in it count as in-box as well: a path is a file the script ships + or references, which the relative-path rule looks at, and a pattern cannot be told apart here. + + .PARAMETER Name + The module name as the script writes it. + + .PARAMETER InboxModule + The names of the in-box modules. + + .EXAMPLE + Test-IslInboxModuleName -Name 'Microsoft.Graph.Authentication' -InboxModule (Get-IslInboxModule) + + $false: the Graph SDK is not in-box. + + .INPUTS + None. + + .OUTPUTS + System.Boolean. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [AllowEmptyString()] + [string]$Name, + + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [string[]]$InboxModule + ) + + # A path is a file the script ships or references, not a module by name; leave it to the + # relative-path rule + if ($Name -match '[\\/]' -or $Name -match '\.psm?1$|\.psd1$') { return $true } + if ($Name -match '[\*\?\$]') { return $true } + $Name -in $InboxModule +} diff --git a/Tests/Unit/Private/Get-IslCredentialArgument.Tests.ps1 b/Tests/Unit/Private/Get-IslCredentialArgument.Tests.ps1 new file mode 100644 index 0000000..6cfa49a --- /dev/null +++ b/Tests/Unit/Private/Get-IslCredentialArgument.Tests.ps1 @@ -0,0 +1,52 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + What a Get-Credential call is handed as its credential, for the interactive-call rule. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + # The syntax tree of a script given as text + function script:ConvertTo-Ast { + param([string]$Text) + [System.Management.Automation.Language.Parser]::ParseInput($Text, [ref]$null, [ref]$null) + } + + function script:Get-Argument { + param([string]$Text) + $commandType = [System.Management.Automation.Language.CommandAst] + $command = (ConvertTo-Ast $Text).Find({ param($node) $node -is $commandType }, $true) + InModuleScope IntuneScriptLab -Parameters @{ Command = $command } { + @(Get-IslCredentialArgument -Command $Command | ForEach-Object { $_.Extent.Text }) + } + } +} + +Describe 'Get-IslCredentialArgument' -Tag 'Unit', 'Private' { + + It 'gives for ' -ForEach @( + @{ Text = 'Get-Credential -Credential $saved'; Expected = '$saved' } + @{ Text = 'Get-Credential -Cred $saved'; Expected = '$saved' } + @{ Text = 'Get-Credential -Credential:$saved'; Expected = '$saved' } + @{ Text = 'Get-Credential $saved'; Expected = '$saved' } + @{ Text = "Get-Credential 'LAB\user'"; Expected = "'LAB\user'" } + ) { + $found = @(Get-Argument -Text $Text) + + $found | Should-BeCollection -Count 1 + $found[0] | Should-Be $Expected + } + + It 'gives nothing for ' -ForEach @( + @{ Text = 'Get-Credential' } + @{ Text = "Get-Credential -Message 'Sign in'" } + @{ Text = "Get-Credential -UserName 'LAB\user'" } + @{ Text = "Get-Credential -Title 'x' -Credential `$saved" } + ) { + Get-Argument -Text $Text | Should-BeCollection @() + } +} diff --git a/Tests/Unit/Private/Get-IslCredentialSource.Tests.ps1 b/Tests/Unit/Private/Get-IslCredentialSource.Tests.ps1 new file mode 100644 index 0000000..6c09139 --- /dev/null +++ b/Tests/Unit/Private/Get-IslCredentialSource.Tests.ps1 @@ -0,0 +1,65 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + How an expression builds a credential, for the interactive-call rule. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + # The syntax tree of a script given as text + function script:ConvertTo-Ast { + param([string]$Text) + [System.Management.Automation.Language.Parser]::ParseInput($Text, [ref]$null, [ref]$null) + } + + function script:Get-Source { + param([string]$Text) + $assignment = (ConvertTo-Ast "`$x = $Text").Find({ + param($node) $node -is [System.Management.Automation.Language.AssignmentStatementAst] + }, $true) + InModuleScope IntuneScriptLab -Parameters @{ Expression = $assignment.Right } { + @(Get-IslCredentialSource -Expression $Expression) + } + } +} + +Describe 'Get-IslCredentialSource' -Tag 'Unit', 'Private' { + + It 'reads as ' -ForEach @( + @{ Text = '[pscredential]::new($user, $secure)'; Expected = '[pscredential]::new()' } + @{ + Text = '[System.Management.Automation.PSCredential]::new($user, $secure)' + Expected = '[pscredential]::new()' + } + @{ Text = 'New-Object PSCredential $user, $secure'; Expected = 'New-Object PSCredential' } + @{ + Text = 'New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $a' + Expected = 'New-Object PSCredential' + } + @{ Text = '[pscredential]$value'; Expected = 'a [pscredential] cast' } + @{ Text = 'Import-Clixml -Path .\cred.xml'; Expected = 'Import-Clixml' } + @{ Text = '(Import-Clixml -Path .\cred.xml)'; Expected = 'Import-Clixml' } + ) { + $source = @(Get-Source -Text $Text) + + $source | Should-BeCollection -Count 1 + $source[0] | Should-Be $Expected + } + + It 'gives nothing for ' -ForEach @( + @{ Text = 'Get-Secret -Name Lab' } + @{ Text = '$other.Credential' } + @{ Text = 'New-Object System.Net.WebClient' } + @{ Text = "'LAB\user'" } + ) { + Get-Source -Text $Text | Should-BeCollection @() + } + + It 'gives nothing for no expression' { + InModuleScope IntuneScriptLab { @(Get-IslCredentialSource -Expression $null) } | Should-BeCollection @() + } +} diff --git a/Tests/Unit/Private/Get-IslReturnReplacement.Tests.ps1 b/Tests/Unit/Private/Get-IslReturnReplacement.Tests.ps1 new file mode 100644 index 0000000..bb0e844 --- /dev/null +++ b/Tests/Unit/Private/Get-IslReturnReplacement.Tests.ps1 @@ -0,0 +1,39 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The edit that says what a script-scope return already does, for the exit-code rule. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + # The syntax tree of a script given as text + function script:ConvertTo-Ast { + param([string]$Text) + [System.Management.Automation.Language.Parser]::ParseInput($Text, [ref]$null, [ref]$null) + } + + function script:Get-Replacement { + param([string]$Text) + $return = (ConvertTo-Ast $Text).Find({ + param($node) $node -is [System.Management.Automation.Language.ReturnStatementAst] + }, $true) + InModuleScope IntuneScriptLab -Parameters @{ Return = $return } { + Get-IslReturnReplacement -Return $Return + } + } +} + +Describe 'Get-IslReturnReplacement' -Tag 'Unit', 'Private' { + + It 'gives for ' -ForEach @( + @{ Text = 'return'; Expected = 'exit 0' } + @{ Text = 'return 1'; Expected = '1; exit 0' } + @{ Text = "return 'installed'"; Expected = "'installed'; exit 0" } + ) { + Get-Replacement -Text $Text | Should-Be $Expected + } +} diff --git a/Tests/Unit/Private/Get-IslVariableCredentialSource.Tests.ps1 b/Tests/Unit/Private/Get-IslVariableCredentialSource.Tests.ps1 new file mode 100644 index 0000000..e1ebc56 --- /dev/null +++ b/Tests/Unit/Private/Get-IslVariableCredentialSource.Tests.ps1 @@ -0,0 +1,60 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + How a variable comes to hold a credential, for the interactive-call rule. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + # The syntax tree of a script given as text + function script:ConvertTo-Ast { + param([string]$Text) + [System.Management.Automation.Language.Parser]::ParseInput($Text, [ref]$null, [ref]$null) + } + + # The source of the variable that Get-Credential is handed in the script + function script:Get-Source { + param([string]$Text) + $ast = ConvertTo-Ast $Text + $call = $ast.Find({ + param($node) + $node -is [System.Management.Automation.Language.CommandAst] -and + $node.GetCommandName() -eq 'Get-Credential' + }, $true) + $variable = $call.CommandElements[-1] + InModuleScope IntuneScriptLab -Parameters @{ Variable = $variable; Ast = $ast } { + @(Get-IslVariableCredentialSource -Variable $Variable -Ast $Ast) + } + } +} + +Describe 'Get-IslVariableCredentialSource' -Tag 'Unit', 'Private' { + + It 'names every way the script builds the credential' { + $text = "if (`$a) { `$cred = Import-Clixml .\c.xml } else { `$cred = [pscredential]::new(`$u, `$p) }`n" + + 'Get-Credential -Credential $cred' + + Get-Source -Text $text | Should-BeCollection @('Import-Clixml, [pscredential]::new()') + } + + It 'takes a typed parameter and a scope prefix' { + $text = "param([pscredential]`$Cred)`n`$script:Cred = Import-Clixml .\c.xml`n" + + 'Get-Credential -Credential $Cred' + + Get-Source -Text $text | Should-BeCollection @('Import-Clixml, a [pscredential] parameter') + } + + It 'gives nothing when one assignment could be something else' { + $text = "`$cred = Import-Clixml .\c.xml`n`$cred = Get-Secret -Name x`nGet-Credential -Credential `$cred" + + Get-Source -Text $text | Should-BeCollection @() + } + + It 'gives nothing for a variable the script never gives a value' { + Get-Source -Text 'Get-Credential -Credential $cred' | Should-BeCollection @() + } +} diff --git a/Tests/Unit/Private/Test-IslExitFollowsReturn.Tests.ps1 b/Tests/Unit/Private/Test-IslExitFollowsReturn.Tests.ps1 new file mode 100644 index 0000000..98e42ca --- /dev/null +++ b/Tests/Unit/Private/Test-IslExitFollowsReturn.Tests.ps1 @@ -0,0 +1,41 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + Whether an exit with another code follows a script-scope return, for the exit-code rule. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + # The syntax tree of a script given as text + function script:ConvertTo-Ast { + param([string]$Text) + [System.Management.Automation.Language.Parser]::ParseInput($Text, [ref]$null, [ref]$null) + } + + function script:Test-FollowingExit { + param([string]$Text) + $return = (ConvertTo-Ast $Text).Find({ + param($node) $node -is [System.Management.Automation.Language.ReturnStatementAst] + }, $true) + InModuleScope IntuneScriptLab -Parameters @{ Return = $return } { + Test-IslExitFollowsReturn -Return $Return + } + } +} + +Describe 'Test-IslExitFollowsReturn' -Tag 'Unit', 'Private' { + + It 'gives for ' -ForEach @( + @{ Case = 'an exit 1 after the return'; Text = "return 'missing'`nexit 1"; Expected = $true } + @{ Case = 'an exit 0 after the return'; Text = "return 'ok'`nexit 0"; Expected = $false } + @{ Case = 'an exit 1 before the return'; Text = "exit 1`nreturn 'ok'"; Expected = $false } + @{ Case = 'no exit at all'; Text = "return 'ok'"; Expected = $false } + @{ Case = 'an exit in another block'; Text = "if (`$a) { return 'ok' }`nexit 1"; Expected = $false } + ) { + Test-FollowingExit -Text $Text | Should-Be $Expected + } +} diff --git a/Tests/Unit/Private/Test-IslInboxModuleName.Tests.ps1 b/Tests/Unit/Private/Test-IslInboxModuleName.Tests.ps1 new file mode 100644 index 0000000..aa705eb --- /dev/null +++ b/Tests/Unit/Private/Test-IslInboxModuleName.Tests.ps1 @@ -0,0 +1,40 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + Whether a module name a script uses is in-box under the agent, for the module-dependency rule. +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + + # The syntax tree of a script given as text + function script:ConvertTo-Ast { + param([string]$Text) + [System.Management.Automation.Language.Parser]::ParseInput($Text, [ref]$null, [ref]$null) + } + + function script:Test-Name { + param([string]$Name) + InModuleScope IntuneScriptLab -Parameters @{ Name = $Name } { + Test-IslInboxModuleName -Name $Name -InboxModule 'Microsoft.PowerShell.Utility', 'Storage' + } + } +} + +Describe 'Test-IslInboxModuleName' -Tag 'Unit', 'Private' { + + It 'gives for ' -ForEach @( + @{ Name = 'Storage'; Expected = $true } + @{ Name = 'storage'; Expected = $true } + @{ Name = 'Microsoft.Graph.Authentication'; Expected = $false } + @{ Name = '.\Helpers\Tools.psm1'; Expected = $true } + @{ Name = 'Tools.psd1'; Expected = $true } + @{ Name = 'Az.*'; Expected = $true } + @{ Name = '$moduleName'; Expected = $true } + ) { + Test-Name -Name $Name | Should-Be $Expected + } +}