diff --git a/powershell/internal/services/azure/Get-MtDefenderForCloudAttackPath.ps1 b/powershell/internal/services/azure/Get-MtDefenderForCloudAttackPath.ps1 new file mode 100644 index 0000000000..ec7772d203 --- /dev/null +++ b/powershell/internal/services/azure/Get-MtDefenderForCloudAttackPath.ps1 @@ -0,0 +1,103 @@ +function Get-MtDefenderForCloudAttackPath { + <# + .SYNOPSIS + Returns the Microsoft Defender for Cloud attack paths grouped by path, together with whether + Defender CSPM is enabled on any readable subscription. + + .DESCRIPTION + Attack paths are computed by Defender CSPM, so an empty result has two very different meanings: + the plan is off and nothing was ever computed, or the plan is on and the estate genuinely has no + path. The returned object separates them. CspmEnabled comes from the Defender for Cloud pricing of + CloudPosture, which Azure Resource Graph exposes as microsoft.security/pricings, so the caller can + report "not licensed" instead of a pass. + + On the fields, measured against a live Defender CSPM subscription rather than assumed: + + - properties.attackPathType is a GUID and properties.displayName is a sentence. The engine + requires an instance ID matching ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$, so the GUID is the ID of + the path type and the sentence is the title. Grouping by the GUID is also what "one result per + attack path type" means: the sentence can repeat across occurrences of the same type. + - properties.entryPoint carries entityInternalId, entityType and dataSource, and no entity name, + so the entry point is reported by its resource type. + - properties.target does carry entityName as well as entityType, so the target is named. + - properties.riskFactors and properties.mITRETacticsAndTechniques.tactics are arrays. Azure + Resource Graph does not support mv-apply, so they are carried as their JSON text and parsed + here. + + .EXAMPLE + Get-MtDefenderForCloudAttackPath + + Returns whether Defender CSPM is on and the attack paths grouped by path. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + # Defender CSPM is the plan that computes attack paths. Its pricing row is the only way to tell an + # estate with no path from a subscription that never had the plan on. + $pricingQuery = @' +securityresources +| where type == "microsoft.security/pricings" +| where name == "CloudPosture" +| summarize StandardCount = countif(tostring(properties.pricingTier) == "Standard") +'@ + + Write-Verbose 'Checking whether Defender CSPM is enabled...' + $pricing = @(Invoke-MtAzureResourceGraphRequest -Query $pricingQuery) | Select-Object -First 1 + $cspmEnabled = $null -ne $pricing -and [int]($pricing.StandardCount) -gt 0 + + $pathQuery = @' +securityresources +| where type == "microsoft.security/attackpaths" +| extend displayName = tostring(properties.displayName), + risk = tostring(properties.riskLevel), + parcial = tostring(properties.isPartialAttackPath), + riskFactors = tostring(properties.riskFactors), + tactics = tostring(properties.mITRETacticsAndTechniques.tactics), + tipoEntrada = tostring(properties.entryPoint.entityType), + targetName = tostring(properties.target.entityName), + tipoDestino = tostring(properties.target.entityType) +// A risk level is per occurrence, so a group holds several. any() picked one at random, and it +// picked independently for the risk factors and the tactics, so the three could describe different +// occurrences of the same attack path type. arg_max takes all three from the one that ranks worst. +| extend riskRank = case(risk =~ "Critical", 4, risk =~ "High", 3, risk =~ "Medium", 2, risk =~ "Low", 1, 0) +| summarize PathCount = count(), + DisplayName = any(displayName), + Partial = any(parcial), + EntryPointTypeList = make_set(tipoEntrada, 10), + TargetList = make_set(targetName, 10), + // make_set is capped, so the consumer needs to know when it is showing a subset. + TargetTotal = dcount(targetName), + TargetTypeList = make_set(tipoDestino, 10), + (RiskRank, RiskLevel, RiskFactorsJson, TacticsJson) = arg_max(riskRank, risk, riskFactors, tactics) + by AttackPathType = tostring(properties.attackPathType) +| project-away RiskRank +| sort by PathCount desc, AttackPathType asc +'@ + + Write-Verbose 'Querying Defender for Cloud attack paths...' + $rows = @(Invoke-MtAzureResourceGraphRequest -Query $pathQuery) + + $paths = [System.Collections.Generic.List[pscustomobject]]::new() + foreach ($row in $rows) { + if (-not $row -or [string]::IsNullOrWhiteSpace([string]$row.AttackPathType)) { continue } + $paths.Add([pscustomobject]@{ + AttackPathType = [string]$row.AttackPathType + DisplayName = [string]$row.DisplayName + RiskLevel = [string]$row.RiskLevel + PathCount = [int]($row.PathCount) + RiskFactorList = ConvertFrom-MtJsonArray -Text ([string]$row.RiskFactorsJson) + TacticList = ConvertFrom-MtJsonArray -Text ([string]$row.TacticsJson) + EntryPointTypeList = @($row.EntryPointTypeList | Where-Object { $_ }) + TargetList = @($row.TargetList | Where-Object { $_ }) + # make_set is capped at 10; this is how many distinct targets there really are. + TargetTotal = [int]($row.TargetTotal) + TargetTypeList = @($row.TargetTypeList | Where-Object { $_ }) + }) + } + + [pscustomobject]@{ + CspmEnabled = $cspmEnabled + PathList = $paths + } +} diff --git a/powershell/internal/services/azure/Get-MtDefenderForCloudRecommendation.ps1 b/powershell/internal/services/azure/Get-MtDefenderForCloudRecommendation.ps1 new file mode 100644 index 0000000000..4bd7b82f37 --- /dev/null +++ b/powershell/internal/services/azure/Get-MtDefenderForCloudRecommendation.ps1 @@ -0,0 +1,97 @@ +function Get-MtDefenderForCloudRecommendation { + <# + .SYNOPSIS + Returns one row per Microsoft Defender for Cloud recommendation across the subscriptions the + signed-in account can read, with how many resources are healthy, unhealthy, not applicable and + exempt. + + .DESCRIPTION + Runs a single Azure Resource Graph query over securityresources, aggregated server side so the + result is one row per recommendation rather than one row per resource and recommendation. A large + estate produces thousands of assessment rows and only hundreds of recommendations, which is the + difference the caller needs to stay readable. + + Each row carries the recommendation's assessment key, display name, severity from its metadata, the + risk level Defender CSPM adds when it is enabled, the portal link, the resource counts, a capped + sample of the unhealthy resource names, and the exemption cause when every resource is exempt. + + An empty result means Defender for Cloud produced no assessment for these subscriptions. The caller + must skip in that case: no unhealthy resource over no assessment is not a pass. + + Errors are deliberately not caught here, so a failed query surfaces instead of being read as a + clean estate. + + .EXAMPLE + Get-MtDefenderForCloudRecommendation + + Returns the Defender for Cloud recommendations with their resource counts. + #> + [CmdletBinding()] + [OutputType([System.Collections.Generic.List[pscustomobject]])] + param() + + # Aggregated server side: one row per assessment key. make_set is capped because a recommendation + # can be unhealthy on thousands of resources and the result is a summary, not an inventory. + $query = @' +securityresources +| where type == "microsoft.security/assessments" +// Multicloud connectors surface AWS and GCP assessments in the same table, and their counts +// would flow into an Azure test. Native Azure resources have no Source, so the empty string is +// kept deliberately: filtering on Source == "Azure" alone would return nothing. +| extend source = tostring(properties.resourceDetails.Source) +| where source == "" or source =~ "Azure" +| extend status = tostring(properties.status.code), + causa = tostring(properties.status.cause), + displayName = tostring(properties.displayName), + severity = tostring(properties.metadata.severity), + risk = tostring(properties.risk.level), + portal = tostring(properties.links.azurePortal) +// A risk level is per resource, so a group holds several. any() picks one at random and could +// report Low for a key that is Critical somewhere. Ranked and maxed, the group reports its worst. +| extend riskRank = case(risk =~ "Critical", 4, risk =~ "High", 3, risk =~ "Medium", 2, risk =~ "Low", 1, 0) +| summarize TotalCount = count(), + UnhealthyCount = countif(status == "Unhealthy"), + HealthyCount = countif(status == "Healthy"), + NotApplicableCount = countif(status == "NotApplicable"), + ExemptCount = countif(causa == "Exempt"), + UnhealthyResourceList = make_set_if(tostring(split(id, "/")[8]), status == "Unhealthy", 10), + UnhealthyResourceTotal = dcountif(tostring(split(id, "/")[8]), status == "Unhealthy"), + // any() is correct for these three: they belong to the assessment definition, so they + // are the same on every row of the group. + DisplayName = any(displayName), + Severity = any(severity), + PortalUri = any(portal), + RiskRank = max(riskRank) + by AssessmentKey = name +| extend RiskLevel = case(RiskRank == 4, "Critical", RiskRank == 3, "High", RiskRank == 2, "Medium", RiskRank == 1, "Low", "") +| project-away RiskRank +| sort by UnhealthyCount desc, AssessmentKey asc +'@ + + Write-Verbose 'Querying Defender for Cloud assessments through Azure Resource Graph...' + $rows = @(Invoke-MtAzureResourceGraphRequest -Query $query) + + $result = [System.Collections.Generic.List[pscustomobject]]::new() + foreach ($row in $rows) { + if (-not $row -or [string]::IsNullOrWhiteSpace([string]$row.AssessmentKey)) { continue } + $result.Add([pscustomobject]@{ + AssessmentKey = [string]$row.AssessmentKey + DisplayName = [string]$row.DisplayName + Severity = [string]$row.Severity + RiskLevel = [string]$row.RiskLevel + PortalUri = [string]$row.PortalUri + TotalCount = [int]($row.TotalCount) + UnhealthyCount = [int]($row.UnhealthyCount) + HealthyCount = [int]($row.HealthyCount) + NotApplicableCount = [int]($row.NotApplicableCount) + ExemptCount = [int]($row.ExemptCount) + UnhealthyResourceList = @($row.UnhealthyResourceList) + # The list above is capped at 10, so the caller can say "10 of 37" instead of + # showing a subset as if it were the whole set. + UnhealthyResourceTotal = [int]($row.UnhealthyResourceTotal) + }) + } + + # -NoEnumerate keeps an empty list from collapsing to $null. + Write-Output $result -NoEnumerate +} diff --git a/powershell/internal/utility/ConvertFrom-MtJsonArray.ps1 b/powershell/internal/utility/ConvertFrom-MtJsonArray.ps1 new file mode 100644 index 0000000000..7b50c0e410 --- /dev/null +++ b/powershell/internal/utility/ConvertFrom-MtJsonArray.ps1 @@ -0,0 +1,25 @@ +function ConvertFrom-MtJsonArray { + <# + .SYNOPSIS + Reads a JSON array that arrived as text and returns its items, or an empty array. + + .DESCRIPTION + Azure Resource Graph has no `mv-apply`, so a query that needs to return an array packs it + into a JSON string. This unpacks it. Empty, whitespace and malformed text all return an + empty array rather than throwing: the caller is building a report row, and a value it + cannot parse is a missing value, not a reason to fail the check. + + .EXAMPLE + ConvertFrom-MtJsonArray -Text '["a","b"]' + + Returns a and b. + #> + [CmdletBinding()] + [OutputType([object[]])] + param( + [string] $Text + ) + + if ([string]::IsNullOrWhiteSpace($Text)) { return @() } + try { return @($Text | ConvertFrom-Json) } catch { return @() } +} diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..c5bece57c1 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -1951,7 +1951,7 @@ "AD" ] }, - "SelectedCount": 609, + "SelectedCount": 611, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2500,6 +2500,8 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1271", + "MT.1272", "ORCA.100", "ORCA.101", "ORCA.102", @@ -2581,7 +2583,7 @@ "AD" ] }, - "SelectedCount": 639, + "SelectedCount": 641, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3162,6 +3164,8 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1271", + "MT.1272", "ORCA.100", "ORCA.101", "ORCA.102", @@ -4006,7 +4010,7 @@ "AD" ] }, - "SelectedCount": 595, + "SelectedCount": 597, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4543,6 +4547,8 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1271", + "MT.1272", "ORCA.100", "ORCA.101", "ORCA.102", diff --git a/powershell/tests/functions/Test-MtAzureDefenderForCloud.Tests.ps1 b/powershell/tests/functions/Test-MtAzureDefenderForCloud.Tests.ps1 new file mode 100644 index 0000000000..0d3bd0f319 --- /dev/null +++ b/powershell/tests/functions/Test-MtAzureDefenderForCloud.Tests.ps1 @@ -0,0 +1,320 @@ +Describe 'Defender for Cloud recommendations and attack paths' { + BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + # Native tests, their instance sources and internal helpers; none is exported. + Use-MtModuleFunction -Name Test-MtAzureDefenderForCloudRecommendation, + Get-MtAzureDefenderForCloudRecommendationInstance, + Test-MtAzureDefenderForCloudAttackPath, + Get-MtAzureDefenderForCloudAttackPathInstance, + Get-MtDefenderForCloudRecommendation, + Get-MtDefenderForCloudAttackPath + + function Get-TestRecommendation { + param( + [int] $Unhealthy = 0, [int] $Healthy = 3, [int] $NotApplicable = 0, [int] $Exempt = 0, + [string] $Severity = 'Medium', [string] $RiskLevel = '' + ) + $total = $Unhealthy + $Healthy + $NotApplicable + return [pscustomobject]@{ + AssessmentKey = '01d9a108-3379-4c5a-8236-1a724dummy' + DisplayName = 'App Service apps should use the latest HTTP version' + Severity = $Severity + RiskLevel = $RiskLevel + PortalUri = 'https://portal.azure.com/#blade/dummy' + TotalCount = $total + UnhealthyCount = $Unhealthy + HealthyCount = $Healthy + NotApplicableCount = $NotApplicable + ExemptCount = $Exempt + UnhealthyResourceList = @('app-01', 'app-02') + } + } + + function Get-TestPath { + param([string] $RiskLevel = 'High') + return [pscustomobject]@{ + AttackPathType = '563f8222-1c75-4d35-3114-588a83b45762' + DisplayName = 'Internet exposed Azure VM allows lateral movement to a storage account' + RiskLevel = $RiskLevel + PathCount = 1 + RiskFactorList = @('Internet exposure', 'Vulnerabilities') + TacticList = @('Lateral Movement', 'Initial Access') + EntryPointTypeList = @('microsoft.compute/virtualmachines') + TargetList = @('storage-01') + TargetTypeList = @('microsoft.storage/storageaccounts') + } + } + } + + BeforeEach { + $script:TestResult = $null + $script:SkippedBecause = $null + $script:SkippedCustomReason = $null + $script:Severity = $null + + Mock -ModuleName Maester Get-MtLicenseInformation { return $true } + Mock -ModuleName Maester Add-MtTestResultDetail { + param($Result, $SkippedBecause, $SkippedCustomReason, $Severity) + + $script:TestResult = $Result + $script:SkippedBecause = $SkippedBecause + $script:SkippedCustomReason = $SkippedCustomReason + $script:Severity = $Severity + } + } + + Context 'MT.1271 recommendations' { + It 'passes when no resource is unhealthy' { + $i = [pscustomobject]@{ Data = Get-TestRecommendation -Unhealthy 0 -Healthy 5 } + + Test-MtAzureDefenderForCloudRecommendation -Instance $i | Should -BeTrue + $script:TestResult | Should -Match 'None is unhealthy' + } + + It 'fails when any resource is unhealthy and names them' { + $i = [pscustomobject]@{ Data = Get-TestRecommendation -Unhealthy 2 -Healthy 1 } + + Test-MtAzureDefenderForCloudRecommendation -Instance $i | Should -BeFalse + $script:TestResult | Should -Match '\*\*2\*\* of them are unhealthy' + $script:TestResult | Should -Match 'app-01, app-02' + } + + It 'skips with the exemption count when every resource is exempt' { + $i = [pscustomobject]@{ Data = Get-TestRecommendation -Unhealthy 0 -Healthy 0 -NotApplicable 4 -Exempt 4 } + + $null -eq (Test-MtAzureDefenderForCloudRecommendation -Instance $i) | Should -BeTrue + $script:SkippedBecause | Should -Be 'Custom' + $script:SkippedCustomReason | Should -Match 'exempt' + } + + It 'skips instead of passing when nothing was evaluated either way' { + # No unhealthy over no evaluated resource is not a pass. + $i = [pscustomobject]@{ Data = Get-TestRecommendation -Unhealthy 0 -Healthy 0 -NotApplicable 6 } + + $null -eq (Test-MtAzureDefenderForCloudRecommendation -Instance $i) | Should -BeTrue + $script:SkippedBecause | Should -Be 'NotApplicable' + } + + # The severity has to be on the instance: the engine resolves config, then the instance, then + # the attribute, so a -Severity passed to Add-MtTestResultDetail is never reached while the + # attribute declares one. Asserting it on the detail is what let this ship the wrong way round. + It 'puts the Defender CSPM risk level on the instance, preferred over the metadata severity' { + Mock -ModuleName Maester Get-MtDefenderForCloudRecommendation { @(Get-TestRecommendation -Unhealthy 1 -Severity 'Low' -RiskLevel 'Critical') } + + $instance = @(Get-MtAzureDefenderForCloudRecommendationInstance)[0] + $instance.Severity | Should -Be 'High' -Because 'Critical maps to High and beats the Low metadata severity' + } + + It 'falls back to the metadata severity on the instance when there is no risk level' { + Mock -ModuleName Maester Get-MtDefenderForCloudRecommendation { @(Get-TestRecommendation -Unhealthy 1 -Severity 'Low' -RiskLevel '') } + + $instance = @(Get-MtAzureDefenderForCloudRecommendationInstance)[0] + $instance.Severity | Should -Be 'Low' + } + + It 'passes no severity to Add-MtTestResultDetail, which the attribute would discard' { + $i = [pscustomobject]@{ Data = Get-TestRecommendation -Unhealthy 1 -Severity 'Low' -RiskLevel 'Critical' } + + $null = Test-MtAzureDefenderForCloudRecommendation -Instance $i + $script:Severity | Should -BeNullOrEmpty + } + + It 'emits one instance per recommendation and none when there is no assessment' { + Mock -ModuleName Maester Get-MtDefenderForCloudRecommendation { @(Get-TestRecommendation), @(Get-TestRecommendation) } + @(Get-MtAzureDefenderForCloudRecommendationInstance).Count | Should -Be 2 + + Mock -ModuleName Maester Get-MtDefenderForCloudRecommendation { @() } + @(Get-MtAzureDefenderForCloudRecommendationInstance).Count | Should -Be 0 + } + } + + Context 'MT.1272 attack paths' { + It 'reports the family as not licensed when Defender CSPM is off' { + # Without the plan no attack path was ever computed, so an empty result says nothing. + Mock -ModuleName Maester Get-MtDefenderForCloudAttackPath { + [pscustomobject]@{ CspmEnabled = $false; PathList = @() } + } + + @(Get-MtAzureDefenderForCloudAttackPathInstance).Count | Should -Be 0 + $script:SkippedBecause | Should -Be 'Custom' + $script:SkippedCustomReason | Should -Match 'Defender CSPM is not enabled' + } + + It 'emits nothing without claiming a licence problem when the plan is on and no path exists' { + Mock -ModuleName Maester Get-MtDefenderForCloudAttackPath { + [pscustomobject]@{ CspmEnabled = $true; PathList = @() } + } + + @(Get-MtAzureDefenderForCloudAttackPathInstance).Count | Should -Be 0 + $script:SkippedCustomReason | Should -BeNullOrEmpty + } + + It 'uses the attack path type GUID as the instance id, not the sentence' { + # The engine requires ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$, which a sentence never matches. + Mock -ModuleName Maester Get-MtDefenderForCloudAttackPath { + [pscustomobject]@{ CspmEnabled = $true; PathList = @(Get-TestPath) } + } + + $instance = @(Get-MtAzureDefenderForCloudAttackPathInstance)[0] + $instance.Id | Should -Match '^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$' + $instance.Title | Should -Match 'Internet exposed Azure VM' + } + + It 'puts the path risk level on the instance, and passes none to Add-MtTestResultDetail' { + Mock -ModuleName Maester Get-MtDefenderForCloudAttackPath { + return [pscustomobject]@{ CspmEnabled = $true; PathList = @(Get-TestPath -RiskLevel 'Medium') } + } + + $instance = @(Get-MtAzureDefenderForCloudAttackPathInstance)[0] + $instance.Severity | Should -Be 'Medium' + + $null = Test-MtAzureDefenderForCloudAttackPath -Instance ([pscustomobject]@{ Data = Get-TestPath -RiskLevel 'Medium' }) + $script:Severity | Should -BeNullOrEmpty + } + + It 'fails for a reported path, with its risk factors and tactics' { + $i = [pscustomobject]@{ Data = Get-TestPath } + + Test-MtAzureDefenderForCloudAttackPath -Instance $i | Should -BeFalse + $script:TestResult | Should -Match 'microsoft.compute/virtualmachines' + $script:TestResult | Should -Match 'Internet exposure, Vulnerabilities' + $script:TestResult | Should -Match 'Lateral Movement, Initial Access' + } + } + + Context 'What the queries ask Azure for' { + # These three aggregations happen server side, so the behaviour lives in the query text + # rather than in PowerShell. Each mock answers the way Azure would for a query that does + # ask, and the way it would for one that does not, so the case fails against the previous + # query instead of asserting on a string. + + It 'takes the worst risk level of a group, not an arbitrary one' { + # `any(risk)` is non-deterministic by contract, so a key that is Critical on one + # resource could be reported Low. Ranked and maxed, the group reports its worst. + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + if ($Query -match 'max\(riskRank\)') { + return @([pscustomobject]@{ AssessmentKey = 'k1'; DisplayName = 'Una recomendacion'; Severity = 'Medium'; RiskLevel = 'Critical'; PortalUri = ''; TotalCount = 2; UnhealthyCount = 1; HealthyCount = 1; NotApplicableCount = 0; ExemptCount = 0; UnhealthyResourceList = @('r1'); UnhealthyResourceTotal = 1 }) + } + return @([pscustomobject]@{ AssessmentKey = 'k1'; DisplayName = 'Una recomendacion'; Severity = 'Medium'; RiskLevel = 'Low'; PortalUri = ''; TotalCount = 2; UnhealthyCount = 1; HealthyCount = 1; NotApplicableCount = 0; ExemptCount = 0; UnhealthyResourceList = @('r1'); UnhealthyResourceTotal = 1 }) + } + + $fila = @(Get-MtDefenderForCloudRecommendation)[0] + $fila.RiskLevel | Should -Be 'Critical' + } + + It 'leaves AWS and GCP assessments out of an Azure test' { + # Multicloud connectors surface their assessments in the same table. The empty Source + # is kept on purpose: native Azure resources have none, so filtering on "Azure" alone + # would return nothing at all. + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + $conFiltro = $Query -match 'source == "" or source =~ "Azure"' + return @([pscustomobject]@{ AssessmentKey = 'k1'; DisplayName = 'Una recomendacion'; Severity = 'Medium'; RiskLevel = 'High'; PortalUri = ''; TotalCount = $(if ($conFiltro) { 2 } else { 5 }); UnhealthyCount = 1; HealthyCount = 1; NotApplicableCount = 0; ExemptCount = 0; UnhealthyResourceList = @('r1'); UnhealthyResourceTotal = 1 }) + } + + $fila = @(Get-MtDefenderForCloudRecommendation)[0] + $fila.TotalCount | Should -Be 2 -Because 'the three AWS and GCP rows must not be counted' + } + + It 'reports how many distinct targets there are, not just the ten it shows' { + # make_set is capped at 10 while PathCount counts everything, so without the total the + # reader cannot tell a complete list from a truncated one. + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + if ($Query -match 'StandardCount') { return @([pscustomobject]@{ StandardCount = 1 }) } + return @([pscustomobject]@{ AttackPathType = 'tipo-1'; DisplayName = 'Un camino'; RiskLevel = 'High'; Partial = 'false'; RiskFactorsJson = '[]'; TacticsJson = '[]'; PathCount = 37; EntryPointTypeList = @('vm'); TargetList = @('t1','t2'); TargetTotal = 37; TargetTypeList = @('storage') }) + } + + # The function returns a wrapper with CspmEnabled and PathList, not the rows. + $fila = @((Get-MtDefenderForCloudAttackPath).PathList)[0] + $fila.TargetTotal | Should -Be 37 + @($fila.TargetList).Count | Should -Be 2 -Because 'the list is a sample and the total says so' + } + } + + Context 'Get-MtDefenderForCloudAttackPath' { + It 'reads CspmEnabled from the CloudPosture pricing tier' { + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + if ($Query -match 'microsoft.security/pricings') { return @([pscustomobject]@{ StandardCount = 1 }) } + return @() + } + + (Get-MtDefenderForCloudAttackPath).CspmEnabled | Should -BeTrue + + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + if ($Query -match 'microsoft.security/pricings') { return @([pscustomobject]@{ StandardCount = 0 }) } + return @() + } + + (Get-MtDefenderForCloudAttackPath).CspmEnabled | Should -BeFalse + } + + It 'parses the risk factors and tactics that arrive as JSON text' { + # Azure Resource Graph has no mv-apply, so the arrays travel as their JSON text. + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + if ($Query -match 'microsoft.security/pricings') { return @([pscustomobject]@{ StandardCount = 1 }) } + return @([pscustomobject]@{ + AttackPathType = '563f8222-1c75-4d35-3114-588a83b45762' + DisplayName = 'A path' + RiskLevel = 'High' + PathCount = 2 + RiskFactorsJson = '["Internet exposure","Plaintext keys"]' + TacticsJson = '["Exfiltration"]' + EntryPointTypeList = @('microsoft.compute/virtualmachines') + TargetList = @('storage-01') + TargetTypeList = @('microsoft.storage/storageaccounts') + }) + } + + $path = (Get-MtDefenderForCloudAttackPath).PathList[0] + $path.RiskFactorList | Should -Contain 'Plaintext keys' + $path.TacticList | Should -Contain 'Exfiltration' + $path.PathCount | Should -Be 2 + } + + It 'survives risk factors that are not valid JSON' { + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + if ($Query -match 'microsoft.security/pricings') { return @([pscustomobject]@{ StandardCount = 1 }) } + return @([pscustomobject]@{ + AttackPathType = 'abc' + DisplayName = 'A path' + RiskLevel = 'Low' + PathCount = 1 + RiskFactorsJson = 'not json at all' + TacticsJson = '' + }) + } + + $path = (Get-MtDefenderForCloudAttackPath).PathList[0] + @($path.RiskFactorList).Count | Should -Be 0 + @($path.TacticList).Count | Should -Be 0 + } + } + + Context 'Get-MtDefenderForCloudRecommendation' { + It 'returns an empty list, not null, when there is no assessment' { + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { @() } + + $r = Get-MtDefenderForCloudRecommendation + $null -eq $r | Should -BeFalse + $r.Count | Should -Be 0 + } + + It 'drops rows without an assessment key and normalises the counts' { + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + @( + [pscustomobject]@{ + AssessmentKey = 'key-1'; DisplayName = 'A'; Severity = 'High'; RiskLevel = 'Medium' + PortalUri = 'https://x'; TotalCount = 7; UnhealthyCount = 3; HealthyCount = 4 + NotApplicableCount = 0; ExemptCount = 0; UnhealthyResourceList = @('r1') + }, + [pscustomobject]@{ AssessmentKey = '' } + ) + } + + $r = Get-MtDefenderForCloudRecommendation + $r.Count | Should -Be 1 + $r[0].UnhealthyCount | Should -Be 3 + $r[0].RiskLevel | Should -Be 'Medium' + } + } +} diff --git a/tests/maester/azure/Test.MT.1271.md b/tests/maester/azure/Test.MT.1271.md new file mode 100644 index 0000000000..8a2e387a0a --- /dev/null +++ b/tests/maester/azure/Test.MT.1271.md @@ -0,0 +1,26 @@ +Ensure no resource is left **unhealthy for a Microsoft Defender for Cloud recommendation**. + +Defender for Cloud assesses the resources of every subscription it covers against a catalogue of recommendations and reports, per recommendation, which resources are healthy. An assessor normally reads that one recommendation at a time in the Azure portal. This check brings it into a Maester run. + +It runs **once per recommendation**, following the `InstanceSource` pattern `MT.1024` introduced — never once per resource. A large estate produces thousands of assessment rows and only hundreds of recommendations, and that difference is what keeps the report readable. + +A recommendation **passes** when no resource is unhealthy and **fails** when any is. The result carries the assessment key, the resource counts, the severity Defender assigns, the Defender CSPM risk level when the plan is on, a sample of up to ten unhealthy resource names, and the portal link to the full list. + +Severity follows the source. Defender CSPM adds a risk level per recommendation and that is preferred when present; otherwise the recommendation's own metadata severity is used. + +## When this is skipped + +- **Every resource is exempt.** An exemption is a decision already recorded in the Azure portal, so the check reports it with the count and does not raise the recommendation again. +- **Nothing was evaluated either way.** When a recommendation has no healthy and no unhealthy resource, there is no outcome to judge and the result is skipped as not applicable. **No unhealthy resource over no evaluated resource is not a pass.** +- **No assessment at all.** When Defender for Cloud returns nothing for the readable subscriptions, the instance source emits nothing and the engine skips the family with `NoInstances`. A subscription with no assessment has no recommendation to comply with. + +## How to remediate + +Open the recommendation in **Microsoft Defender for Cloud** → **Recommendations** and either remediate the resources listed or exempt the recommendation there, so the decision is recorded in the portal rather than lost. + +## Permissions + +Read-only. Reader or Security Reader on the subscriptions, or on a management group above them. The query runs through Azure Resource Graph, so it covers every readable subscription in one call. + + +%TestResult% diff --git a/tests/maester/azure/Test.MT.1271.ps1 b/tests/maester/azure/Test.MT.1271.ps1 new file mode 100644 index 0000000000..f6d3e3a866 --- /dev/null +++ b/tests/maester/azure/Test.MT.1271.ps1 @@ -0,0 +1,170 @@ +function Get-MtAzureDefenderForCloudRecommendationInstance { + <# + .SYNOPSIS + Returns one MT.1271 instance per Microsoft Defender for Cloud recommendation. + + .DESCRIPTION + Instance source of the MT.1271 family. The suffix is the recommendation's assessment key + (MT.1271.) and the title names the recommendation, the way MT.1024 does for Entra + recommendations. One instance per recommendation, never one per resource: a large estate produces + thousands of assessment rows and only hundreds of recommendations. + + When Defender for Cloud returns no assessment at all the source emits nothing and the engine skips + the family with NoInstances. A subscription with no assessment has no recommendation to comply + with, and must never be reported as having none unhealthy. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + $recommendations = Get-MtDefenderForCloudRecommendation + + foreach ($recommendation in $recommendations) { + # A recommendation evaluated against no resource has no outcome to judge. + if ($recommendation.TotalCount -le 0) { continue } + + $name = if ([string]::IsNullOrWhiteSpace($recommendation.DisplayName)) { + $recommendation.AssessmentKey + } else { + $recommendation.DisplayName + } + + # Severity follows the source, as #2510 asks. It goes on the instance because that is where the + # engine reads a family's per-instance severity (Invoke-MtNativePlan resolves config, then the + # instance, then the attribute); -Severity on Add-MtTestResultDetail is never reached once the + # attribute declares one. + # The Defender CSPM risk level is preferred when present, otherwise the recommendation's own + # metadata severity. + $source = if (-not [string]::IsNullOrWhiteSpace($recommendation.RiskLevel)) { $recommendation.RiskLevel } else { $recommendation.Severity } + $severity = switch -Regex ($source) { + '^(Critical|High)$' { 'High'; break } + '^Medium$' { 'Medium'; break } + '^Low$' { 'Low'; break } + default { 'Medium' } + } + + [pscustomobject]@{ + Id = $recommendation.AssessmentKey + Title = "No resource should be left unhealthy for the Defender for Cloud recommendation '$name'." + Severity = $severity + Data = $recommendation + } + } +} + +function Test-MtAzureDefenderForCloudRecommendation { + <# + .SYNOPSIS + Ensure no resource is left unhealthy for a Microsoft Defender for Cloud recommendation. + + .DESCRIPTION + Defender for Cloud assesses the resources of every subscription it covers against a catalogue of + recommendations and reports, per recommendation, which resources are healthy. An assessor normally + reads that one recommendation at a time in the Azure portal. This check brings it into a Maester + run. + + It runs once per recommendation, following the InstanceSource pattern MT.1024 introduced. A + recommendation passes when no resource is unhealthy and fails when any is, with the resource + counts, a sample of the unhealthy resource names and the portal link to the full list. + + Severity follows the source, as #2510 asks. Defender CSPM adds a risk level per recommendation, + and that is preferred when present; otherwise the recommendation's own metadata severity is used. + + A recommendation whose resources are all exempt is skipped with the exemption cause, so a decision + already recorded in the Azure portal is respected rather than reported again. A recommendation that + applies to nothing is skipped as not applicable. Neither is reported as a pass. + + .OUTPUTS + [bool] - True when no resource is unhealthy, false when any is, null when skipped. + + .EXAMPLE + Test-MtAzureDefenderForCloudRecommendation + + Returns one result per Defender for Cloud recommendation. + + .LINK + https://maester.dev/docs/commands/Test-MtAzureDefenderForCloudRecommendation + #> + [MaesterTest( + Id = 'MT.1271', + Title = 'Resources should be healthy for the Microsoft Defender for Cloud recommendations.', + Product = 'azure', + RelatedProduct = 'defender', + Feature = 'subscriptions', + Area = 'infrastructure', + ResourceType = 'AzureResource', + Severity = 'Medium', + UserImpact = 'Low', + ImplementationCost = 'Medium', + Mitre = 'None', + Service = 'Azure', + Lifecycle = 'Preview', + InstanceSource = 'Get-MtAzureDefenderForCloudRecommendationInstance', + Author = 'earbona23' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # The recommendation to check, supplied by the engine. + $Instance + ) + + $recommendation = $Instance.Data + $unhealthy = [int]$recommendation.UnhealthyCount + $healthy = [int]$recommendation.HealthyCount + $notApplicable = [int]$recommendation.NotApplicableCount + $exempt = [int]$recommendation.ExemptCount + $total = [int]$recommendation.TotalCount + + if ($exempt -gt 0 -and $exempt -eq $total) { + # Every resource is exempt, which is a decision already recorded in the Azure portal. Respect + # it instead of reporting the recommendation again. + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Every resource for this recommendation is exempt in Defender for Cloud ($exempt of $total)." + return $null + } + + if ($unhealthy -eq 0 -and $healthy -eq 0) { + # Nothing was evaluated either way. No unhealthy resource over no evaluated resource is not a + # pass. + Add-MtTestResultDetail -SkippedBecause NotApplicable + return $null + } + + $testResult = $unhealthy -eq 0 + + $testResultMarkdown = "Defender for Cloud assessed **$total** resource(s) for this recommendation. " + if ($testResult) { + $testResultMarkdown += "None is unhealthy.`n`n" + } else { + $testResultMarkdown += "**$unhealthy** of them are unhealthy.`n`n" + } + + $testResultMarkdown += "| Property | Value |`n| --- | --- |`n" + $testResultMarkdown += "| Assessment key | ``$($recommendation.AssessmentKey)`` |`n" + $testResultMarkdown += "| Unhealthy | $unhealthy |`n" + $testResultMarkdown += "| Healthy | $healthy |`n" + $testResultMarkdown += "| Not applicable | $notApplicable |`n" + if ($exempt -gt 0) { $testResultMarkdown += "| Exempt | $exempt |`n" } + if (-not [string]::IsNullOrWhiteSpace($recommendation.Severity)) { $testResultMarkdown += "| Severity in Defender for Cloud | $($recommendation.Severity) |`n" } + if (-not [string]::IsNullOrWhiteSpace($recommendation.RiskLevel)) { $testResultMarkdown += "| Risk level (Defender CSPM) | $($recommendation.RiskLevel) |`n" } + + if (-not $testResult) { + $resources = @($recommendation.UnhealthyResourceList | Where-Object { $_ }) + if ($resources.Count -gt 0) { + # "up to ten shown" does not tell the reader whether ten is all of them. The total does. + $resourceLabel = if ([int]$recommendation.UnhealthyResourceTotal -gt $resources.Count) { "$($resources.Count) of $([int]$recommendation.UnhealthyResourceTotal)" } else { 'all' } + # Resource names come from the tenant, so they are escaped before reaching Markdown. + $safeResources = @($resources | ForEach-Object { Get-MtSafeMarkdown $_ }) + $testResultMarkdown += "`nUnhealthy resources ($resourceLabel): $($safeResources -join ', ')`n" + } + if (-not [string]::IsNullOrWhiteSpace($recommendation.PortalUri)) { + $testResultMarkdown += "`n[Open this recommendation in the Azure portal]($($recommendation.PortalUri))`n" + } + $testResultMarkdown += "`nRemediate the resources listed, or exempt the recommendation in Defender for Cloud so the decision is recorded there." + } else { + $testResultMarkdown += "`nWell done. Every resource Defender for Cloud evaluated for this recommendation is healthy." + } + + Add-MtTestResultDetail -Result $testResultMarkdown + return $testResult +} diff --git a/tests/maester/azure/Test.MT.1272.md b/tests/maester/azure/Test.MT.1272.md new file mode 100644 index 0000000000..37a558fcff --- /dev/null +++ b/tests/maester/azure/Test.MT.1272.md @@ -0,0 +1,34 @@ +Ensure Microsoft Defender for Cloud reports **no active attack path**. + +Defender CSPM correlates the weaknesses of an estate into attack paths: a chain that starts at something an attacker can reach and ends at something worth reaching. An individual recommendation rates each weakness on its own; the **path** is what makes the combination matter. A virtual machine with a known vulnerability is one finding, a storage account holding a connection string is another, and the path that joins them is the thing an attacker actually walks. + +This check runs **once per attack path** Defender for Cloud reports, and **fails** for each one, because an attack path is an active route rather than a configuration opinion. + +The result names the entry point's resource type, the target, the risk factors Defender combined and the MITRE tactics the path covers. + +Severity follows the source: the risk level Defender assigns to the path. + +## On the fields + +Measured against a live Defender CSPM subscription rather than assumed: + +- `properties.attackPathType` is a **GUID** and `properties.displayName` is a sentence. The engine requires an instance ID matching `^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`, so the GUID identifies the path type and the sentence is the title. Grouping by the GUID is also what *"one result per attack path type"* means. +- `properties.entryPoint` carries `entityInternalId`, `entityType` and `dataSource`, and **no entity name**, so the entry point is reported by its resource type. +- `properties.target` does carry `entityName` as well as `entityType`, so the target is named. +- `properties.riskFactors` and `properties.mITRETacticsAndTechniques.tactics` are arrays, and Azure Resource Graph has no `mv-apply`, so they travel as JSON text and are parsed in the helper. + +## When this is skipped + +- **Defender CSPM is not enabled** on any readable subscription. No attack path was ever computed, so an empty result says nothing about the estate. The family reports that instead of a pass, read from the `CloudPosture` pricing tier. +- **The plan is on and no path exists.** The instance source emits nothing and the engine skips the family with `NoInstances`. That is genuinely good news, and it is reported as "nothing to judge" rather than as a passing check, because this family has one result per path and no path to attach a pass to. + +## How to remediate + +Break the path rather than every weakness on it. Removing the entry point's exposure, or the credential or permission that allows the step to the target, closes the whole route. Defender for Cloud lists the recommendations that make up each path in the Azure portal, under **Attack path analysis**. + +## Permissions + +Read-only. Reader or Security Reader on the subscriptions, plus the **Defender CSPM** plan enabled. + + +%TestResult% diff --git a/tests/maester/azure/Test.MT.1272.ps1 b/tests/maester/azure/Test.MT.1272.ps1 new file mode 100644 index 0000000000..81557041b6 --- /dev/null +++ b/tests/maester/azure/Test.MT.1272.ps1 @@ -0,0 +1,136 @@ +function Get-MtAzureDefenderForCloudAttackPathInstance { + <# + .SYNOPSIS + Returns one MT.1272 instance per Microsoft Defender for Cloud attack path. + + .DESCRIPTION + Instance source of the MT.1272 family. One instance per attack path, titled with the path itself, + which Defender for Cloud phrases as a sentence naming the entry point and the target. + + When Defender CSPM is not enabled on any readable subscription the source reports the family as not + licensed, because no attack path was ever computed and an empty result there says nothing about the + estate. When the plan is on and no path exists the source emits nothing and the engine skips the + family with NoInstances. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + $attackPaths = Get-MtDefenderForCloudAttackPath + + if (-not $attackPaths.CspmEnabled) { + # Attack paths are computed by Defender CSPM. Without the plan there is nothing to read, and an + # empty result must not be read as an estate with no attack path. + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Defender CSPM is not enabled on any readable subscription, so Defender for Cloud computes no attack paths.' + return + } + + foreach ($path in $attackPaths.PathList) { + # The engine requires an instance ID matching ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$, so the ID is + # the attack path type's GUID and the sentence Defender writes is the title. + # Severity follows the source, as #2510 asks. It goes on the instance because that is where the + # engine reads a family's per-instance severity (Invoke-MtNativePlan resolves config, then the + # instance, then the attribute); -Severity on Add-MtTestResultDetail is never reached once the + # attribute declares one. + # The risk level Defender assigns to the path. + $severity = switch -Regex ([string]$path.RiskLevel) { + '^(Critical|High)$' { 'High'; break } + '^Medium$' { 'Medium'; break } + '^Low$' { 'Low'; break } + default { 'High' } + } + + [pscustomobject]@{ + Id = $path.AttackPathType + Title = "No active attack path should exist: $($path.DisplayName)" + Severity = $severity + Data = $path + } + } +} + +function Test-MtAzureDefenderForCloudAttackPath { + <# + .SYNOPSIS + Ensure Microsoft Defender for Cloud reports no active attack path to a critical asset. + + .DESCRIPTION + Defender CSPM correlates the weaknesses of an estate into attack paths: a chain that starts at + something an attacker can reach and ends at something worth reaching. An individual recommendation + rates each weakness on its own, and the path is what makes the combination matter. + + This check runs once per attack path Defender for Cloud reports, and fails for each one, because an + attack path is by definition an active route rather than a configuration opinion. The result names + the entry point's resource type, the target, the risk factors Defender combined, and the MITRE + tactics the path covers. + + Severity follows the source: the risk level Defender assigns to the path. + + It never passes on an absent source. Without Defender CSPM on a readable subscription no path was + ever computed, and the family reports that rather than a clean estate. + + .OUTPUTS + [bool] - Always false for a reported path; null when the family is skipped. + + .EXAMPLE + Test-MtAzureDefenderForCloudAttackPath + + Returns one result per attack path Defender for Cloud reports. + + .LINK + https://maester.dev/docs/commands/Test-MtAzureDefenderForCloudAttackPath + #> + [MaesterTest( + Id = 'MT.1272', + Title = 'Microsoft Defender for Cloud should report no active attack path.', + Product = 'azure', + RelatedProduct = 'defender', + Feature = 'subscriptions', + Area = 'infrastructure', + ResourceType = 'AzureResource', + Severity = 'High', + UserImpact = 'Low', + ImplementationCost = 'Medium', + Mitre = ('T1190', 'T1552'), + Service = 'Azure', + Lifecycle = 'Preview', + InstanceSource = 'Get-MtAzureDefenderForCloudAttackPathInstance', + Author = 'earbona23' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # The attack path to report, supplied by the engine. + $Instance + ) + + $path = $Instance.Data + + $testResultMarkdown = "Defender for Cloud reports this attack path on **$($path.PathCount)** occasion(s).`n`n" + $testResultMarkdown += "| Property | Value |`n| --- | --- |`n" + if (-not [string]::IsNullOrWhiteSpace($path.RiskLevel)) { $testResultMarkdown += "| Risk level | $($path.RiskLevel) |`n" } + + $entry = @($path.EntryPointTypeList | Where-Object { $_ }) + if ($entry.Count -gt 0) { $testResultMarkdown += "| Entry point resource type | $($entry -join ', ') |`n" } + $target = @($path.TargetList | Where-Object { $_ }) + if ($target.Count -gt 0) { + # The list is capped server side, so say when it is a sample. Without this the reader + # cannot tell ten targets from ten of thirty-seven. + $targetLabel = if ([int]$path.TargetTotal -gt $target.Count) { "Target ($($target.Count) of $([int]$path.TargetTotal))" } else { 'Target' } + # Target names are tenant resources, so they are escaped before reaching Markdown. + $safeTargets = @($target | ForEach-Object { Get-MtSafeMarkdown $_ }) + $testResultMarkdown += "| $targetLabel | $($safeTargets -join ', ') |`n" + } + $targetType = @($path.TargetTypeList | Where-Object { $_ }) + if ($targetType.Count -gt 0) { $testResultMarkdown += "| Target resource type | $($targetType -join ', ') |`n" } + + $factors = @($path.RiskFactorList | Where-Object { $_ }) + if ($factors.Count -gt 0) { $testResultMarkdown += "`n**Risk factors Defender combined.** $($factors -join ', ')`n" } + $tactics = @($path.TacticList | Where-Object { $_ }) + if ($tactics.Count -gt 0) { $testResultMarkdown += "`n**MITRE tactics.** $($tactics -join ', ')`n" } + + $testResultMarkdown += "`nBreak the path rather than every weakness on it. Removing the entry point's exposure, or the credential or permission that allows the step to the target, closes the whole route; Defender for Cloud lists the recommendations of this path in the Azure portal." + + Add-MtTestResultDetail -Result $testResultMarkdown + return $false +}