diff --git a/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 b/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 new file mode 100644 index 0000000000..e6f2882cac --- /dev/null +++ b/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 @@ -0,0 +1,137 @@ +function Get-MtAzureSecureScore { + <# + .SYNOPSIS + Returns one row per Azure subscription with the Microsoft Defender for Cloud secure score and the + state of the regulatory compliance standards assigned to it. + + .DESCRIPTION + Runs three Azure Resource Graph queries over the subscriptions the signed-in account can read: the + secure score per subscription, the regulatory compliance standards per subscription, and the + subscription names from ResourceContainers so the result names a subscription instead of only its + GUID. + + The percentage is computed from the current and maximum score rather than read from + properties.score.percentage, whose unit the Azure samples present two different ways: the secure + score page divides current by max itself while the Resource Graph sample projects the property + directly. Dividing here removes the ambiguity. + + A subscription with a maximum score of zero is still returned. Defender for Cloud produced a score + row for it but assessed nothing, and the caller must say so rather than drop the subscription + silently or read it as a pass. + + An empty secure score result means Defender for Cloud produced no score for these subscriptions. + The caller must skip in that case. + + Errors are deliberately not caught here, so a failed query surfaces instead of being read as an + estate with no score. + + .EXAMPLE + Get-MtAzureSecureScore + + Returns the secure score and compliance standards of each readable subscription. + #> + [CmdletBinding()] + [OutputType([System.Collections.Generic.List[pscustomobject]])] + param() + + # The name filter is not cosmetic. Score resources are per initiative, and the instance ID for + # this family is the subscription ID, so a second initiative in one subscription would produce a + # repeated instance ID. Invoke-MtNativePlan returns a single InvalidInstanceId Error row for the + # whole family in that case and evaluates nothing, so one extra initiative anywhere in the estate + # would take MT.1266 out everywhere. 'ascScore' is the ASC Default initiative, per the Azure API. + # properties.score.max is cast because the score arrives as a dynamic value. + $scoreQuery = @' +securityresources +| where type == "microsoft.security/securescores" +| where name == "ascScore" +| extend currentScore = todouble(properties.score.current), + maxScore = todouble(properties.score.max), + initiative = tostring(properties.displayName) +| project subscriptionId, currentScore, maxScore, initiative +| sort by subscriptionId asc +'@ + + # The standards level already carries the control counts this needs, so there is no reason to read + # the control level and aggregate it back up. + $standardQuery = @' +securityresources +| where type == "microsoft.security/regulatorycompliancestandards" +| extend standard = name, + state = tostring(properties.state), + passedControls = toint(properties.passedControls), + failedControls = toint(properties.failedControls), + skippedControls = toint(properties.skippedControls), + unsupportedControls = toint(properties.unsupportedControls) +| project subscriptionId, standard, state, passedControls, failedControls, skippedControls, unsupportedControls +| sort by subscriptionId asc, standard asc +'@ + + $nameQuery = @' +resourcecontainers +| where type == "microsoft.resources/subscriptions" +| project subscriptionId, subscriptionName = name +'@ + + Write-Verbose 'Querying the Defender for Cloud secure score through Azure Resource Graph...' + $scoreRows = @(Invoke-MtAzureResourceGraphRequest -Query $scoreQuery) + + $result = [System.Collections.Generic.List[pscustomobject]]::new() + if ($scoreRows.Count -eq 0) { + # -NoEnumerate keeps an empty list from collapsing to $null. + Write-Output $result -NoEnumerate + return + } + + Write-Verbose 'Querying the regulatory compliance standards...' + $standardRows = @(Invoke-MtAzureResourceGraphRequest -Query $standardQuery) + Write-Verbose 'Querying the subscription names...' + $nameRows = @(Invoke-MtAzureResourceGraphRequest -Query $nameQuery) + + $nameLookup = @{} + foreach ($row in $nameRows) { + if (-not $row -or [string]::IsNullOrWhiteSpace([string]$row.subscriptionId)) { continue } + $nameLookup[[string]$row.subscriptionId] = [string]$row.subscriptionName + } + + $standardLookup = @{} + foreach ($row in $standardRows) { + if (-not $row -or [string]::IsNullOrWhiteSpace([string]$row.subscriptionId)) { continue } + $id = [string]$row.subscriptionId + if (-not $standardLookup.ContainsKey($id)) { + $standardLookup[$id] = [System.Collections.Generic.List[pscustomobject]]::new() + } + $standardLookup[$id].Add([pscustomobject]@{ + Standard = [string]$row.standard + State = [string]$row.state + PassedControls = [int]($row.passedControls) + FailedControls = [int]($row.failedControls) + SkippedControls = [int]($row.skippedControls) + UnsupportedControls = [int]($row.unsupportedControls) + }) + } + + foreach ($row in $scoreRows) { + if (-not $row -or [string]::IsNullOrWhiteSpace([string]$row.subscriptionId)) { continue } + $id = [string]$row.subscriptionId + $current = [double]($row.currentScore) + $max = [double]($row.maxScore) + # A maximum of zero means nothing was assessed. Reporting 0% there would read as a bad score + # rather than as no score, so the percentage stays null and the caller skips the subscription. + # Not rounded: the caller compares it with the target, and 79.96 rounded to 80.0 would pass a target + # of 80. Round only for display. Decimal, not double: in double 57 of 100 is 56.99999999999999 and would + # miss a target of 57. + $percentage = if ($max -gt 0) { [double]([decimal]$current * 100 / [decimal]$max) } else { $null } + + $result.Add([pscustomobject]@{ + SubscriptionId = $id + SubscriptionName = if ($nameLookup.ContainsKey($id)) { $nameLookup[$id] } else { $id } + Initiative = [string]$row.initiative + CurrentScore = $current + MaxScore = $max + ScorePercentage = $percentage + StandardList = if ($standardLookup.ContainsKey($id)) { @($standardLookup[$id]) } else { @() } + }) + } + + Write-Output $result -NoEnumerate +} diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..30ef273af4 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -1951,7 +1951,7 @@ "AD" ] }, - "SelectedCount": 609, + "SelectedCount": 610, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2500,6 +2500,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1266", "ORCA.100", "ORCA.101", "ORCA.102", @@ -2581,7 +2582,7 @@ "AD" ] }, - "SelectedCount": 639, + "SelectedCount": 640, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3162,6 +3163,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1266", "ORCA.100", "ORCA.101", "ORCA.102", @@ -4006,7 +4008,7 @@ "AD" ] }, - "SelectedCount": 595, + "SelectedCount": 596, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4543,6 +4545,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1266", "ORCA.100", "ORCA.101", "ORCA.102", diff --git a/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 b/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 new file mode 100644 index 0000000000..a5126eff79 --- /dev/null +++ b/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 @@ -0,0 +1,245 @@ +Describe 'Azure secure score and regulatory compliance' { + BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + # Native test, its instance source and the internal helper; none is exported. + Use-MtModuleFunction -Name Test-MtAzureSecureScore, + Get-MtAzureSecureScoreInstance, + Get-MtAzureSecureScore + + function Get-TestSubscription { + param( + [double] $Current = 44, [double] $Max = 55, [string] $Name = 'Contoso Production', + [object] $Percentage = 80, [object[]] $Standards = $null + ) + if ($null -eq $Standards) { + $Standards = @( + [pscustomobject]@{ Standard = 'Azure-Security-Benchmark'; State = 'Failed'; PassedControls = 30; FailedControls = 4; SkippedControls = 1; UnsupportedControls = 0 } + ) + } + return [pscustomobject]@{ + SubscriptionId = '11111111-2222-3333-4444-555555555555' + SubscriptionName = $Name + Initiative = 'ascScore' + CurrentScore = $Current + MaxScore = $Max + ScorePercentage = $Percentage + StandardList = @($Standards) + } + } + } + + BeforeEach { + $script:TestResult = $null + $script:SkippedBecause = $null + $script:SkippedCustomReason = $null + $script:Severity = $null + + Mock -ModuleName Maester Add-MtTestResultDetail { + param($Result, $SkippedBecause, $SkippedCustomReason, $Severity) + + $script:TestResult = $Result + $script:SkippedBecause = $SkippedBecause + $script:SkippedCustomReason = $SkippedCustomReason + $script:Severity = $Severity + } + } + + Context 'MT.1266 secure score' { + It 'passes at the target and fails below it' { + $at = [pscustomobject]@{ Data = Get-TestSubscription -Percentage 80 } + Test-MtAzureSecureScore -Instance $at | Should -BeTrue -Because '80 meets a target of 80' + + $below = [pscustomobject]@{ Data = Get-TestSubscription -Percentage 79.9 } + Test-MtAzureSecureScore -Instance $below | Should -BeFalse + } + + It 'fails a score just under the target, and shows it under the target' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Percentage 79.96 } + + Test-MtAzureSecureScore -Instance $i | Should -BeFalse -Because '79.96 is below a target of 80' + $script:TestResult | Should -Match 'is \*\*79\.9%\*\*' + } + + It 'honours a target other than the default' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Percentage 85 } + + Test-MtAzureSecureScore -Instance $i -MinimumScorePercentage 90 | Should -BeFalse + Test-MtAzureSecureScore -Instance $i -MinimumScorePercentage 80 | Should -BeTrue + $script:TestResult | Should -Match 'against a target of \*\*80%\*\*' + } + + It 'skips with a reason when Defender for Cloud assessed nothing, rather than reporting zero' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Current 0 -Max 0 -Percentage $null } + + Test-MtAzureSecureScore -Instance $i | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'Custom' + $script:SkippedCustomReason | Should -Match 'maximum secure score is zero' + $script:TestResult | Should -BeNullOrEmpty -Because 'a skip reports the reason, not a score table' + } + + It 'escapes the subscription name in the skip reason too, not only in the result' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Current 0 -Max 0 -Percentage $null -Name '[Sign in again](https://phish.example)' } + + $null = Test-MtAzureSecureScore -Instance $i + $script:SkippedCustomReason | Should -Not -Match '\[Sign in again\]\(https' + $script:SkippedCustomReason | Should -Match '\\\[Sign in again\\\]' + } + + It 'reports the compliance standards as a summary, worst first' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Standards @( + [pscustomobject]@{ Standard = 'Azure-CIS-1.4.0'; State = 'Failed'; PassedControls = 10; FailedControls = 2; SkippedControls = 0; UnsupportedControls = 1 }, + [pscustomobject]@{ Standard = 'Azure-Security-Benchmark'; State = 'Failed'; PassedControls = 30; FailedControls = 9; SkippedControls = 1; UnsupportedControls = 0 } + ) } + + $null = Test-MtAzureSecureScore -Instance $i + $script:TestResult | Should -Match 'Regulatory compliance standards assigned to this subscription' + $benchmarkRow = ([regex]::Match($script:TestResult, '(?m)^\| Azure-Security-Benchmark .*$')).Index + $cisRow = ([regex]::Match($script:TestResult, '(?m)^\| Azure-CIS-1\\?\.4\\?\.0 .*$')).Index + $benchmarkRow | Should -BeLessThan $cisRow -Because 'nine failed controls outrank two' + } + + It 'says so when no standard is assigned, instead of showing an empty table' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Standards @() } + + $null = Test-MtAzureSecureScore -Instance $i + $script:TestResult | Should -Match 'No regulatory compliance standard is assigned' + $script:TestResult | Should -Not -Match '\| Standard \| State \|' + } + + It 'escapes a subscription name that contains markdown, so it cannot render as a link' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Name '[Sign in again](https://phish.example)' } + + $null = Test-MtAzureSecureScore -Instance $i + $script:TestResult | Should -Not -Match '\[Sign in again\]\(https' + $script:TestResult | Should -Match '\\\[Sign in again\\\]' + } + } + + Context 'Get-MtAzureSecureScoreInstance (MT.1266 instance source)' { + It 'emits one instance per subscription, and none when there is no score' { + Mock -ModuleName Maester Get-MtAzureSecureScore { @(Get-TestSubscription), @(Get-TestSubscription) } + @(Get-MtAzureSecureScoreInstance).Count | Should -Be 2 + + Mock -ModuleName Maester Get-MtAzureSecureScore { @() } + @(Get-MtAzureSecureScoreInstance).Count | Should -Be 0 + } + + It 'uses the subscription id as the instance id and names the subscription in the title' { + Mock -ModuleName Maester Get-MtAzureSecureScore { @(Get-TestSubscription -Name 'Contoso Production') } + + $instance = @(Get-MtAzureSecureScoreInstance)[0] + $instance.Id | Should -Be '11111111-2222-3333-4444-555555555555' + $instance.Title | Should -Match "subscription 'Contoso Production'" + } + } + + Context 'Get-MtAzureSecureScore' { + BeforeEach { + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + param($Query) + + if ($Query -match 'securescores') { + return @([pscustomobject]@{ subscriptionId = 'sub-1'; currentScore = 44; maxScore = 55; initiative = 'ascScore' }, + [pscustomobject]@{ subscriptionId = 'sub-2'; currentScore = 0; maxScore = 0; initiative = 'ascScore' }) + } + if ($Query -match 'regulatorycompliancestandards') { + return @([pscustomobject]@{ subscriptionId = 'sub-1'; standard = 'Azure-Security-Benchmark'; state = 'Failed'; passedControls = 30; failedControls = 4; skippedControls = 1; unsupportedControls = 0 }) + } + return @([pscustomobject]@{ subscriptionId = 'sub-1'; subscriptionName = 'Contoso Production' }) + } + } + + It 'computes the percentage from the current and maximum score' { + # No @(): the helper writes the list with -NoEnumerate, so @() would wrap it in a single + # element and the filter would see the whole list rather than its rows. + $rows = Get-MtAzureSecureScore + + ($rows | Where-Object { $_.SubscriptionId -eq 'sub-1' }).ScorePercentage | Should -Be 80 -Because '44 of 55 is 80%' + } + + It 'returns the percentage unrounded, so the test compares the exact value with the target' -ForEach @( + @{ Current = 79.96; Max = 100; Expected = 79.96 } + @{ Current = 57; Max = 100; Expected = 57 } + @{ Current = 1; Max = 3; Expected = 100 / 3 } + ) { + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + param($Query) + if ($Query -match 'securescores') { return @([pscustomobject]@{ subscriptionId = 'sub-1'; currentScore = $Current; maxScore = $Max; initiative = 'ascScore' }) } + return @() + }.GetNewClosure() + + # No @(): the helper writes the list with -NoEnumerate. + $rows = Get-MtAzureSecureScore + + ($rows | Where-Object { $_.SubscriptionId -eq 'sub-1' }).ScorePercentage | Should -Be $Expected + } + + It 'leaves the percentage null when the maximum score is zero, rather than reporting zero per cent' { + # No @(): the helper writes the list with -NoEnumerate, so @() would wrap it in a single + # element and the filter would see the whole list rather than its rows. + $rows = Get-MtAzureSecureScore + + ($rows | Where-Object { $_.SubscriptionId -eq 'sub-2' }).ScorePercentage | Should -BeNullOrEmpty + } + + It 'falls back to the subscription id when the name is not readable' { + # No @(): the helper writes the list with -NoEnumerate, so @() would wrap it in a single + # element and the filter would see the whole list rather than its rows. + $rows = Get-MtAzureSecureScore + + ($rows | Where-Object { $_.SubscriptionId -eq 'sub-2' }).SubscriptionName | Should -Be 'sub-2' + } + + It 'attaches the standards to their own subscription only' { + # No @(): the helper writes the list with -NoEnumerate, so @() would wrap it in a single + # element and the filter would see the whole list rather than its rows. + $rows = Get-MtAzureSecureScore + + @(($rows | Where-Object { $_.SubscriptionId -eq 'sub-1' }).StandardList).Count | Should -Be 1 + @(($rows | Where-Object { $_.SubscriptionId -eq 'sub-2' }).StandardList).Count | Should -Be 0 + } + + It 'asks Azure for the default initiative only, so one subscription cannot yield two rows' { + # The instance ID for this family is the subscription ID, so two score rows for one + # subscription would repeat it, and Invoke-MtNativePlan answers a repeated instance ID + # with a single InvalidInstanceId Error row for the WHOLE family: one extra initiative + # anywhere would take MT.1266 out across the estate. Score resources are per initiative, + # so the query has to ask for the ASC Default one by name. + # + # The mock honours the filter instead of asserting on the query text: without the + # name filter it answers with the two rows Azure would really return, and this test + # fails. That is the point of writing it this way. + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + param($Query) + + if ($Query -match 'securescores') { + if ($Query -match 'name == "ascScore"') { + return @([pscustomobject]@{ subscriptionId = 'sub-1'; currentScore = 44; maxScore = 55; initiative = 'ASC Default' }) + } + + return @([pscustomobject]@{ subscriptionId = 'sub-1'; currentScore = 44; maxScore = 55; initiative = 'ASC Default' }, + [pscustomobject]@{ subscriptionId = 'sub-1'; currentScore = 10; maxScore = 90; initiative = 'Custom initiative' }) + } + if ($Query -match 'regulatorycompliancestandards') { return @() } + return @([pscustomobject]@{ subscriptionId = 'sub-1'; subscriptionName = 'Contoso Production' }) + } + + # No @(): the helper writes the list with -NoEnumerate, so @() would wrap it in a single + # element and the filter would see the whole list rather than its rows. + $rows = Get-MtAzureSecureScore + + @($rows | Where-Object { $_.SubscriptionId -eq 'sub-1' }).Count | Should -Be 1 -Because 'one subscription is one instance, whatever initiatives it carries' + ($rows | Where-Object { $_.SubscriptionId -eq 'sub-1' }).ScorePercentage | Should -Be 80 -Because 'the default initiative is the one that counts' + } + + It 'returns an empty list, not null, when there is no secure score, and asks for nothing else' { + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { @() } + + $rows = Get-MtAzureSecureScore + $null -ne $rows | Should -BeTrue + @($rows).Count | Should -Be 0 + Should -Invoke -ModuleName Maester Invoke-MtAzureResourceGraphRequest -Times 1 -Exactly -Because 'without a score there is nothing to enrich' + } + } +} diff --git a/tests/maester/azure/Test.MT.1266.md b/tests/maester/azure/Test.MT.1266.md new file mode 100644 index 0000000000..7d555a1b55 --- /dev/null +++ b/tests/maester/azure/Test.MT.1266.md @@ -0,0 +1,36 @@ +Ensure every Azure subscription **meets the Microsoft Defender for Cloud secure score target**. + +Defender for Cloud scores every subscription it covers against its recommendations and expresses the result as a percentage of the maximum achievable score. An assessor reads that number first and the individual recommendations afterwards. This check brings the number into a Maester run, **one result per subscription**, and carries the state of the regulatory compliance standards assigned to that subscription in the same result. + +A subscription **passes** when its secure score reaches the target and **fails** below it. The target is a business decision rather than a vendor rule, so it is a parameter: **80%** by default. + +```powershell +# Raise the bar for one subscription in the Maester config +TestSettings = @( + @{ Id = 'MT.1266.00000000-0000-0000-0000-000000000000'; Parameters = @{ MinimumScorePercentage = 90 } } +) +``` + +The percentage is computed from the current and maximum score rather than read from `properties.score.percentage`, whose unit the Azure samples present two different ways — the secure score page divides current by max itself while the Resource Graph sample projects the property directly. Dividing removes the ambiguity. + +## Regulatory compliance + +The standards assigned to the subscription are reported as a **summary table**: state, and how many controls passed, failed, were skipped or are unsupported. They are deliberately not separate results. The controls behind those numbers are the Defender for Cloud recommendations that `MT.1257` already reports one by one, and raising them again here would count the same finding twice. + +The Microsoft cloud security benchmark is assigned by default, so an empty list usually means it was removed rather than that nothing applies. Other standards, such as CIS Azure, need Defender CSPM. + +## When this is skipped + +- **The maximum score is zero.** Defender for Cloud produced a score row for the subscription but assessed nothing in it, so there is no percentage to compare. The subscription is still reported, with that reason: **no score is not a score of zero, and it is not a pass.** +- **No score at all.** When Defender for Cloud returns no secure score for the readable subscriptions, the instance source emits nothing and the engine skips the family with `NoInstances`. A tenant with no scored subscription has no score to meet. + +## How to remediate + +Open **Microsoft Defender for Cloud** → **Secure score**, which lists the security controls by how many points each would add. The points are weighted, so the controls at the top of that list move the number furthest. `MT.1257` reports the individual recommendations behind each control. + +## Permissions + +Read-only. Reader or Security Reader on the subscriptions, or on a management group above them. The queries run through Azure Resource Graph, so they cover every readable subscription in three calls regardless of how many subscriptions there are. + + +%TestResult% diff --git a/tests/maester/azure/Test.MT.1266.ps1 b/tests/maester/azure/Test.MT.1266.ps1 new file mode 100644 index 0000000000..ed665b01cb --- /dev/null +++ b/tests/maester/azure/Test.MT.1266.ps1 @@ -0,0 +1,146 @@ +function Get-MtAzureSecureScoreInstance { + <# + .SYNOPSIS + Returns one MT.1266 instance per Azure subscription Microsoft Defender for Cloud scores. + + .DESCRIPTION + Instance source of the MT.1266 family. The suffix is the subscription ID (MT.1266.) + and the title names the subscription, so each subscription carries its own result and its own + history. + + Every subscription Defender for Cloud scored is emitted, including one whose maximum score is zero. + That subscription is skipped by the test with a reason rather than dropped here: a subscription the + user knows exists should not vanish from the report. + + When Defender for Cloud returns no score at all the source emits nothing and the engine skips the + family with NoInstances. A tenant with no scored subscription has no score to meet, and must never + be reported as meeting it. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + $scores = Get-MtAzureSecureScore + + foreach ($subscription in $scores) { + [pscustomobject]@{ + Id = $subscription.SubscriptionId + Title = "The Defender for Cloud secure score of subscription '$($subscription.SubscriptionName)' should meet the target." + Data = $subscription + } + } +} + +function Test-MtAzureSecureScore { + <# + .SYNOPSIS + Checks that an Azure subscription meets the Microsoft Defender for Cloud secure score target. + + .DESCRIPTION + Defender for Cloud scores every subscription it covers against its recommendations and expresses the + result as a percentage of the maximum achievable score. An assessor reads that number first and the + individual recommendations afterwards. This check brings the number into a Maester run, one result + per subscription, and carries the state of the regulatory compliance standards assigned to that + subscription in the same result. + + A subscription passes when its secure score reaches MinimumScorePercentage and fails below it. The + target is a business decision rather than a vendor rule, so it is a parameter: 80 by default, and a + TestSettings row in the config can set another value per subscription instance. + + The regulatory compliance standards are reported as a summary table, not as separate results. Each + standard's controls are already covered by the Defender for Cloud recommendation check (MT.1257), + and reporting them twice would double count the same finding. + + .PARAMETER MinimumScorePercentage + The secure score percentage a subscription must reach to pass. 80 by default. + + .PARAMETER Instance + The subscription to check, supplied by the engine. + + .OUTPUTS + [bool] - True when the subscription reaches the target, false when it does not, null when skipped. + + .EXAMPLE + Test-MtAzureSecureScore + + Returns one result per scored Azure subscription. + + .LINK + https://maester.dev/docs/commands/Test-MtAzureSecureScore + #> + [MaesterTest( + Id = 'MT.1266', + Title = 'Azure subscriptions should meet the Microsoft Defender for Cloud secure score target.', + Product = 'azure', + RelatedProduct = 'defender', + Feature = 'subscriptions', + Area = 'infrastructure', + ResourceType = 'AzureResource', + Severity = 'Medium', + UserImpact = 'Low', + ImplementationCost = 'Medium', + Mitre = 'None', + Service = 'Azure', + Permission = 'Azure:Role:Reader | Azure:Role:Security Reader', + Lifecycle = 'Preview', + InstanceSource = 'Get-MtAzureSecureScoreInstance', + Author = 'earbona23' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # The secure score percentage a subscription must reach to pass. + [ValidateRange(0, 100)] + [int] $MinimumScorePercentage = 80, + + # The subscription to check, supplied by the engine. + $Instance + ) + + $subscription = $Instance.Data + $name = Get-MtSafeMarkdown ([string]$subscription.SubscriptionName) + + if ($null -eq $subscription.ScorePercentage) { + # Defender for Cloud produced a score row with a maximum of zero, so it assessed nothing in this + # subscription. No score is not a score of zero, and it is certainly not a pass. + # $name, not the raw SubscriptionName: the reason is rendered as markdown like any other result + # text, and a subscription name is tenant-controlled. + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Defender for Cloud assessed nothing in subscription '$name': its maximum secure score is zero, so there is no percentage to compare." + return $null + } + + # Compare the exact percentage. The one shown is cut, not rounded, to one decimal, so a score just under the + # target never reads as reaching it (79.96 shows as 79.9, not 80). + $testResult = [double]$subscription.ScorePercentage -ge $MinimumScorePercentage + $percentage = [math]::Floor([double]$subscription.ScorePercentage * 10) / 10 + + $testResultMarkdown = "The Defender for Cloud secure score of **$name** is **$percentage%**, against a target of **$MinimumScorePercentage%**.`n`n" + $testResultMarkdown += "| Property | Value |`n| --- | --- |`n" + $testResultMarkdown += "| Subscription | $name |`n" + $testResultMarkdown += "| Subscription ID | ``$($subscription.SubscriptionId)`` |`n" + $testResultMarkdown += "| Secure score | $($subscription.CurrentScore) of $($subscription.MaxScore) points |`n" + $testResultMarkdown += "| Percentage | $percentage% |`n" + $testResultMarkdown += "| Target | $MinimumScorePercentage% |`n" + + $standards = @($subscription.StandardList | Where-Object { $_ -and -not [string]::IsNullOrWhiteSpace($_.Standard) }) + if ($standards.Count -gt 0) { + $testResultMarkdown += "`n**Regulatory compliance standards assigned to this subscription.** Reported as a summary: the controls behind these numbers are covered by MT.1257, and repeating them here would count the same finding twice.`n`n" + $testResultMarkdown += "| Standard | State | Passed | Failed | Skipped | Unsupported |`n| --- | --- | --- | --- | --- | --- |`n" + foreach ($standard in ($standards | Sort-Object -Property @{ Expression = { [int]$_.FailedControls } ; Descending = $true }, Standard)) { + $standardName = Get-MtSafeMarkdown ([string]$standard.Standard) + $state = Get-MtSafeMarkdown ([string]$standard.State) + $testResultMarkdown += "| $standardName | $state | $($standard.PassedControls) | $($standard.FailedControls) | $($standard.SkippedControls) | $($standard.UnsupportedControls) |`n" + } + } else { + $testResultMarkdown += "`nNo regulatory compliance standard is assigned to this subscription. The Microsoft cloud security benchmark is assigned by default, so an empty list usually means it was removed.`n" + } + + if ($testResult) { + $testResultMarkdown += "`nWell done. This subscription is at or above the secure score target." + } else { + $testResultMarkdown += "`nRaise the score in **Microsoft Defender for Cloud** → **Secure score**, which lists the controls by how many points each would add. The points are weighted, so the controls at the top of that list move the number furthest." + } + + Add-MtTestResultDetail -Result $testResultMarkdown + return $testResult +} diff --git a/website/src/data/test-builder.json b/website/src/data/test-builder.json index 2b025d35ea..a63c0e6742 100644 --- a/website/src/data/test-builder.json +++ b/website/src/data/test-builder.json @@ -18524,6 +18524,11 @@ "type": "int", "tests": 1 }, + { + "name": "MinimumScorePercentage", + "type": "int", + "tests": 1 + }, { "name": "ParkedDomains", "type": "string[]",