Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): this line is 111 characters, and the rest of the entry wraps at about 100. The overlong line from the previous extraction is carried along rather than rewrapped. Fix: rewrap the paragraph.

advanced function with help and tests (#65). Nothing changes for a caller: a settings value that
is not allowed still ends `Test-IntuneScript` with `SettingsInvalid,Test-IntuneScript`.
- The README's section headings no longer carry the version that introduced each feature, the
Expand Down
52 changes: 52 additions & 0 deletions Private/Get-IslCredentialArgument.ps1
Original file line number Diff line number Diff line change
@@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-existing (not from this change, not blocking): a switch parameter counts as taking the next value. Get-Credential -Verbose $saved binds $saved to -Credential positionally, but -Verbose is a CommandParameterAst with no Argument, so $saved is passed over and the function gives nothing. The rule then reports a call that does not prompt as an interactive call. Get-IslCredentialSource has the same test for New-Object (New-Object -Verbose PSCredential $u, $p). Fix: leave out the common switches (Verbose, Debug, and so on) from the "takes a value" check, and add a test case for it.

if (-not $taken) { return $element }
}
}
79 changes: 79 additions & 0 deletions Private/Get-IslCredentialSource.ps1
Original file line number Diff line number Diff line change
@@ -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' }
}
}
}
33 changes: 33 additions & 0 deletions Private/Get-IslReturnReplacement.ps1
Original file line number Diff line number Diff line change
@@ -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' }
}
72 changes: 72 additions & 0 deletions Private/Get-IslVariableCredentialSource.ps1
Original file line number Diff line number Diff line change
@@ -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 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-existing (not from this change, not blocking): the help promises that "every value the script gives" the variable is a credential, but only plain AssignmentStatementAsts and parameters are checked. A variable can also get a value from a multiple assignment ($user, $cred = ..., where the left side is an ArrayLiteralAst), a foreach ($cred in ...) loop, -OutVariable cred or Set-Variable. Take a script with $cred = Import-Clixml .\c.xml in one branch and $user, $cred = 'LAB\a', 'LAB\b' in another: it gets Import-Clixml as its source, so Get-Credential -Credential $cred is treated as built, even though it can prompt for a user name. Fix: give nothing when the variable is also a target of an ArrayLiteralAst assignment, a ForEachStatementAst variable, or an -OutVariable/-Variable argument. At least narrow the help to say which forms are read.

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 ', ' }
}
27 changes: 4 additions & 23 deletions Private/Rules/Find-IslExitCodeIssue.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down
Loading