From 150bfc1c18a1193a83ba27b458eb3b02fb4e7be0 Mon Sep 17 00:00:00 2001 From: Eduard Arbona Date: Thu, 5 Nov 2026 23:22:58 -0400 Subject: [PATCH 01/14] feat(defender): device security recommendations and exploitable vulnerabilities (#2517) Implements #2517 under the #2510 epic: bring Defender Vulnerability Management's own findings on devices into a Maester run. - MT.1255 Test-MtDefenderDeviceSecurityRecommendation: one result per assessed security configuration, following the InstanceSource pattern of MT.1024. A configuration passes when every device it applies to complies with it and fails when any applicable device does not, naming the count, the risk and up to ten devices. Severity follows the source: Defender's own rated impact on the configuration score, 8 or more High, 4 to 7 Medium, below 4 Low. - MT.1256 Test-MtDefenderExploitableSoftwareVulnerability: fails when any onboarded device runs software with a high or critical vulnerability whose exploit code is publicly available. Both honour the epic's decisions: - Opt-in, not on by default. Both declare Lifecycle = 'Preview', so neither runs in a default Invoke-Maester. - No new permission. Both go through security/runHuntingQuery with ThreatHunting.Read.All, which is already in the default scopes of Get-MtGraphScope, as the issue proposes. Nothing is added to the default or preview scopes. - License-aware. Both declare License = 'DEFENDER_XDR', so a tenant without a Defender XDR workload is skipped as not licensed, never failed. - Neither passes on an unassessed fleet. MT.1255's instance source emits nothing when Defender returns no assessment, so the engine skips the family with NoInstances. MT.1256 carries the number of devices Defender has vulnerability data for as a denominator and skips when it is zero: zero exposed devices out of zero assessed devices is not a pass. On the signal for MT.1256: the issue names the CISA KEV catalogue, and the advanced hunting schema exposes no CISA KEV flag. DeviceTvmSoftwareVulnerabilitiesKB carries CveId, CvssScore, IsExploitAvailable, VulnerabilitySeverityLevel, LastModifiedTime, PublishedDate, VulnerabilityDescription and AffectedSoftware, and nothing else. IsExploitAvailable, documented as "whether exploit code for the vulnerability is publicly available", is the closest first-party signal and is what the check reports. It does not claim CISA KEV membership. Both helpers aggregate server side, so one hunting query returns one row per configuration and one summary row respectively, rather than one row per device. Errors are not caught in the helpers: Invoke-MtGraphSecurityQuery throws on a query execution error, and letting that surface keeps a broken query from being reported as a clean tenant. Unit tests: 16, covering the pass, fail, severity mapping, risk-only-on-failure, instance emission, empty assessment, inapplicable configuration, name fallback, unassessed fleet, no result set and the row normalisation of both helpers. --- ...Get-MtDefenderExploitableVulnerability.ps1 | 72 +++++ ...tDefenderSecureConfigurationAssessment.ps1 | 75 ++++++ .../tests/fixtures/golden/selection.json | 12 +- ...tDefenderVulnerabilityManagement.Tests.ps1 | 246 ++++++++++++++++++ tests/maester/defender/Test.MT.1255.md | 27 ++ tests/maester/defender/Test.MT.1255.ps1 | 137 ++++++++++ tests/maester/defender/Test.MT.1256.md | 27 ++ tests/maester/defender/Test.MT.1256.ps1 | 103 ++++++++ 8 files changed, 696 insertions(+), 3 deletions(-) create mode 100644 powershell/internal/services/defender/Get-MtDefenderExploitableVulnerability.ps1 create mode 100644 powershell/internal/services/defender/Get-MtDefenderSecureConfigurationAssessment.ps1 create mode 100644 powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 create mode 100644 tests/maester/defender/Test.MT.1255.md create mode 100644 tests/maester/defender/Test.MT.1255.ps1 create mode 100644 tests/maester/defender/Test.MT.1256.md create mode 100644 tests/maester/defender/Test.MT.1256.ps1 diff --git a/powershell/internal/services/defender/Get-MtDefenderExploitableVulnerability.ps1 b/powershell/internal/services/defender/Get-MtDefenderExploitableVulnerability.ps1 new file mode 100644 index 0000000000..83640d92c1 --- /dev/null +++ b/powershell/internal/services/defender/Get-MtDefenderExploitableVulnerability.ps1 @@ -0,0 +1,72 @@ +function Get-MtDefenderExploitableVulnerability { + <# + .SYNOPSIS + Returns a single summary of the devices that run software with a high or critical vulnerability for + which exploit code is publicly available. + + .DESCRIPTION + Runs one advanced hunting query that joins DeviceTvmSoftwareVulnerabilities to + DeviceTvmSoftwareVulnerabilitiesKB and keeps the vulnerabilities whose IsExploitAvailable is true, + at high or critical severity. + + The returned object always carries AssessedDeviceCount: the number of distinct devices Defender + Vulnerability Management has any vulnerability data for. That is the denominator, and it is what lets + the caller tell "no device is exposed" from "nothing has been assessed". A summarize without a by + clause returns exactly one row even over no input, so the denominator comes back either way. + + Note on the signal: the advanced hunting schema exposes no CISA KEV flag. The closest first-party + signal is IsExploitAvailable in DeviceTvmSoftwareVulnerabilitiesKB, documented as "whether exploit + code for the vulnerability is publicly available", and that is what this uses. The check does not + claim CISA KEV membership. + + Errors are deliberately not caught here. Invoke-MtGraphSecurityQuery throws on a query execution + error, and letting that surface keeps a broken query from being reported as a clean fleet. + + .EXAMPLE + Get-MtDefenderExploitableVulnerability + + Returns the exposed device count, the CVE count and the denominator of assessed devices. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + # The denominator is computed first and attached to the single summary row, so an unassessed tenant + # is distinguishable from a clean one. Sets are capped: the result is a summary, not an inventory. + $query = @' +let assessed = toscalar(DeviceTvmSoftwareVulnerabilities | summarize dcount(DeviceId)); +DeviceTvmSoftwareVulnerabilities +| where VulnerabilitySeverityLevel in ('High', 'Critical') +| join kind=inner ( + DeviceTvmSoftwareVulnerabilitiesKB + | where IsExploitAvailable == true + | project CveId, CvssScore + ) on CveId +| summarize ExposedDeviceCount = dcount(DeviceId), + CveCount = dcount(CveId), + TopDeviceList = make_set(DeviceName, 10), + TopCveList = make_set(CveId, 10), + TopSoftwareList = make_set(strcat(SoftwareVendor, ' ', SoftwareName), 10) +| extend AssessedDeviceCount = assessed +'@ + + Write-Verbose 'Querying Defender Vulnerability Management software vulnerabilities...' + $rows = @(Invoke-MtGraphSecurityQuery -Query $query -Timespan 'P1D') + + # The query shape guarantees one row. If the call came back with nothing at all, Defender returned + # no result set and the caller must skip rather than read that as a clean fleet. + $row = $rows | Select-Object -First 1 + if (-not $row) { + Write-Verbose 'No result set returned; the caller reports a skip.' + return $null + } + + [pscustomobject]@{ + AssessedDeviceCount = [int]($row.AssessedDeviceCount) + ExposedDeviceCount = [int]($row.ExposedDeviceCount) + CveCount = [int]($row.CveCount) + TopDeviceList = @($row.TopDeviceList) + TopCveList = @($row.TopCveList) + TopSoftwareList = @($row.TopSoftwareList) + } +} diff --git a/powershell/internal/services/defender/Get-MtDefenderSecureConfigurationAssessment.ps1 b/powershell/internal/services/defender/Get-MtDefenderSecureConfigurationAssessment.ps1 new file mode 100644 index 0000000000..fa9c64568c --- /dev/null +++ b/powershell/internal/services/defender/Get-MtDefenderSecureConfigurationAssessment.ps1 @@ -0,0 +1,75 @@ +function Get-MtDefenderSecureConfigurationAssessment { + <# + .SYNOPSIS + Returns one row per Defender Vulnerability Management security configuration, with how many devices + it applies to and how many of those are not compliant with it. + + .DESCRIPTION + Runs a single advanced hunting query over DeviceTvmSecureConfigurationAssessment, joined to + DeviceTvmSecureConfigurationAssessmentKB for the configuration's name, description, risk and impact. + The aggregation happens server side, so the result is one row per configuration rather than one row + per device and configuration. + + Only configurations Defender reports as applicable to at least one device are returned. A + configuration that applies to nothing cannot be complied with or breached, so it has no outcome to + judge. + + An empty result means Defender Vulnerability Management has no assessment data for this tenant, + typically because no device is onboarded to Defender for Endpoint. The caller must skip in that case: + "no configuration is non-compliant" over zero assessed configurations is not a pass. + + Errors are deliberately not caught here. Invoke-MtGraphSecurityQuery throws on a query execution + error, and letting that surface keeps a broken query from being reported as a clean tenant. + + .EXAMPLE + Get-MtDefenderSecureConfigurationAssessment + + Returns the security configurations assessed in the tenant with their non-compliant device counts. + #> + [CmdletBinding()] + [OutputType([System.Collections.Generic.List[pscustomobject]])] + param() + + # Aggregated server side: one row per configuration. make_set_if is capped so a configuration that + # is non-compliant on thousands of devices does not drag the whole result set back. + $query = @' +DeviceTvmSecureConfigurationAssessment +| where IsApplicable == true +| summarize ApplicableDeviceCount = dcount(DeviceId), + NonCompliantDeviceCount = dcountif(DeviceId, IsCompliant == false), + NonCompliantDeviceList = make_set_if(DeviceName, IsCompliant == false, 10), + ConfigurationCategory = any(ConfigurationCategory), + ConfigurationSubcategory = any(ConfigurationSubcategory) + by ConfigurationId +| join kind=leftouter ( + DeviceTvmSecureConfigurationAssessmentKB + | project ConfigurationId, ConfigurationName, ConfigurationDescription, RiskDescription, ConfigurationImpact + ) on ConfigurationId +| project-away ConfigurationId1 +| sort by NonCompliantDeviceCount desc, ConfigurationImpact desc +'@ + + Write-Verbose 'Querying Defender Vulnerability Management secure configuration assessment...' + $rows = @(Invoke-MtGraphSecurityQuery -Query $query -Timespan 'P1D') + + $result = [System.Collections.Generic.List[pscustomobject]]::new() + foreach ($row in $rows) { + if (-not $row -or [string]::IsNullOrWhiteSpace([string]$row.ConfigurationId)) { continue } + $result.Add([pscustomobject]@{ + ConfigurationId = [string]$row.ConfigurationId + Name = [string]$row.ConfigurationName + Description = [string]$row.ConfigurationDescription + RiskDescription = [string]$row.RiskDescription + Category = [string]$row.ConfigurationCategory + Subcategory = [string]$row.ConfigurationSubcategory + Impact = [double]($row.ConfigurationImpact) + ApplicableDeviceCount = [int]($row.ApplicableDeviceCount) + NonCompliantDeviceCount = [int]($row.NonCompliantDeviceCount) + NonCompliantDeviceList = @($row.NonCompliantDeviceList) + }) + } + + # -NoEnumerate keeps an empty list from collapsing to $null, so the caller can tell an empty + # assessment from a list it can iterate. + Write-Output $result -NoEnumerate +} diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index 05f976972c..a3e5bf5472 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -1918,7 +1918,7 @@ "AD" ] }, - "SelectedCount": 588, + "SelectedCount": 590, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2445,6 +2445,8 @@ "MT.1250", "MT.1251", "MT.1252", + "MT.1255", + "MT.1256", "MT.1260", "ORCA.100", "ORCA.101", @@ -2527,7 +2529,7 @@ "AD" ] }, - "SelectedCount": 618, + "SelectedCount": 620, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3086,6 +3088,8 @@ "MT.1250", "MT.1251", "MT.1252", + "MT.1255", + "MT.1256", "MT.1260", "ORCA.100", "ORCA.101", @@ -3920,7 +3924,7 @@ "AD" ] }, - "SelectedCount": 574, + "SelectedCount": 576, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4435,6 +4439,8 @@ "MT.1250", "MT.1251", "MT.1252", + "MT.1255", + "MT.1256", "MT.1260", "ORCA.100", "ORCA.101", diff --git a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 new file mode 100644 index 0000000000..6fa0f1b61a --- /dev/null +++ b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 @@ -0,0 +1,246 @@ +Describe 'Defender Vulnerability Management device recommendations and exploitable vulnerabilities' { + BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + # These functions became native tests, an instance source and internal helpers; none is exported. + Use-MtModuleFunction -Name Test-MtDefenderDeviceSecurityRecommendation, + Get-MtDefenderDeviceSecurityRecommendationInstance, + Test-MtDefenderExploitableSoftwareVulnerability, + Get-MtDefenderSecureConfigurationAssessment, + Get-MtDefenderExploitableVulnerability + + function Get-TestConfiguration { + param( + [string] $Name = 'Enable Microsoft Defender Antivirus', + [int] $Applicable = 10, + [int] $NonCompliant = 0, + [double] $Impact = 5, + [string[]] $NonCompliantDevices = @() + ) + return [pscustomobject]@{ + ConfigurationId = 'scid-' + [guid]::NewGuid().ToString() + Name = $Name + Description = 'Description of the configuration.' + RiskDescription = 'Risk of leaving it unconfigured.' + Category = 'Security controls' + Subcategory = 'Antivirus' + Impact = $Impact + ApplicableDeviceCount = $Applicable + NonCompliantDeviceCount = $NonCompliant + NonCompliantDeviceList = $NonCompliantDevices + } + } + + function Get-TestVulnerabilitySummary { + param( + [int] $Assessed = 100, + [int] $Exposed = 0, + [int] $CveCount = 0 + ) + return [pscustomobject]@{ + AssessedDeviceCount = $Assessed + ExposedDeviceCount = $Exposed + CveCount = $CveCount + TopDeviceList = @('device-1', 'device-2') + TopCveList = @('CVE-2026-0001') + TopSoftwareList = @('Vendor Product') + } + } + } + + BeforeEach { + $script:TestResult = $null + $script:SkippedBecause = $null + $script:Severity = $null + + Mock -ModuleName Maester Get-MtLicenseInformation { return $true } + Mock -ModuleName Maester Add-MtTestResultDetail { + param($Result, $SkippedBecause, $Severity) + + $script:TestResult = $Result + $script:SkippedBecause = $SkippedBecause + $script:Severity = $Severity + } + } + + Context 'Test-MtDefenderDeviceSecurityRecommendation (MT.1255)' { + It 'passes when every applicable device complies' { + $instance = [pscustomobject]@{ Data = Get-TestConfiguration -Applicable 25 -NonCompliant 0 } + + Test-MtDefenderDeviceSecurityRecommendation -Instance $instance | Should -BeTrue + $script:TestResult | Should -Match 'All of them comply' + } + + It 'fails when any applicable device does not comply' { + $instance = [pscustomobject]@{ + Data = Get-TestConfiguration -Applicable 25 -NonCompliant 4 -NonCompliantDevices @('a', 'b') + } + + Test-MtDefenderDeviceSecurityRecommendation -Instance $instance | Should -BeFalse + $script:TestResult | Should -Match '\*\*4\*\* of them do not comply' + $script:TestResult | Should -Match 'Non-compliant devices \(up to ten shown\): a, b' + } + + It 'takes the severity from the impact Defender reports' { + foreach ($case in @( + @{ Impact = 9; Expected = 'High' }, + @{ Impact = 8; Expected = 'High' }, + @{ Impact = 7; Expected = 'Medium' }, + @{ Impact = 4; Expected = 'Medium' }, + @{ Impact = 3; Expected = 'Low' }, + @{ Impact = 1; Expected = 'Low' } + )) { + $instance = [pscustomobject]@{ Data = Get-TestConfiguration -Impact $case.Impact } + $null = Test-MtDefenderDeviceSecurityRecommendation -Instance $instance + $script:Severity | Should -Be $case.Expected -Because "an impact of $($case.Impact) maps to $($case.Expected)" + } + } + + It 'reports the risk description only when the configuration fails' { + $passing = [pscustomobject]@{ Data = Get-TestConfiguration -NonCompliant 0 } + $null = Test-MtDefenderDeviceSecurityRecommendation -Instance $passing + $script:TestResult | Should -Not -Match 'Risk of leaving it unconfigured' + + $failing = [pscustomobject]@{ Data = Get-TestConfiguration -NonCompliant 1 } + $null = Test-MtDefenderDeviceSecurityRecommendation -Instance $failing + $script:TestResult | Should -Match 'Risk of leaving it unconfigured' + } + } + + Context 'Get-MtDefenderDeviceSecurityRecommendationInstance (MT.1255 instance source)' { + It 'emits one instance per assessed configuration' { + Mock -ModuleName Maester Get-MtDefenderSecureConfigurationAssessment { + @(Get-TestConfiguration -Name 'One'), @(Get-TestConfiguration -Name 'Two') + } + + $instances = @(Get-MtDefenderDeviceSecurityRecommendationInstance) + $instances.Count | Should -Be 2 + $instances[0].Title | Should -Match "Defender recommendation 'One'" + } + + It 'emits nothing when Defender has no assessment, so the family is skipped and not passed' { + Mock -ModuleName Maester Get-MtDefenderSecureConfigurationAssessment { @() } + + @(Get-MtDefenderDeviceSecurityRecommendationInstance).Count | Should -Be 0 + } + + It 'leaves out a configuration that applies to no device' { + Mock -ModuleName Maester Get-MtDefenderSecureConfigurationAssessment { + @(Get-TestConfiguration -Applicable 0) + } + + @(Get-MtDefenderDeviceSecurityRecommendationInstance).Count | Should -Be 0 + } + + It 'falls back to the configuration id when the knowledge base has no name' { + Mock -ModuleName Maester Get-MtDefenderSecureConfigurationAssessment { + $configuration = Get-TestConfiguration + $configuration.Name = '' + @($configuration) + } + + $instance = @(Get-MtDefenderDeviceSecurityRecommendationInstance)[0] + $instance.Title | Should -Match $instance.Id + } + } + + Context 'Test-MtDefenderExploitableSoftwareVulnerability (MT.1256)' { + It 'passes when no assessed device is exposed' { + Mock -ModuleName Maester Get-MtDefenderExploitableVulnerability { + Get-TestVulnerabilitySummary -Assessed 100 -Exposed 0 + } + + Test-MtDefenderExploitableSoftwareVulnerability | Should -BeTrue + $script:TestResult | Should -Match 'None of them runs software' + } + + It 'fails when any assessed device is exposed, with the share' { + Mock -ModuleName Maester Get-MtDefenderExploitableVulnerability { + Get-TestVulnerabilitySummary -Assessed 200 -Exposed 10 -CveCount 7 + } + + Test-MtDefenderExploitableSoftwareVulnerability | Should -BeFalse + $script:TestResult | Should -Match '\*\*10\*\* of them \(5%\)' + $script:TestResult | Should -Match 'CVE-2026-0001' + } + + It 'skips instead of passing when nothing has been assessed' { + # Zero exposed out of zero assessed is not a pass. + Mock -ModuleName Maester Get-MtDefenderExploitableVulnerability { + Get-TestVulnerabilitySummary -Assessed 0 -Exposed 0 + } + + $null -eq (Test-MtDefenderExploitableSoftwareVulnerability) | Should -BeTrue + $script:SkippedBecause | Should -Be 'NotApplicable' + } + + It 'skips when Defender returns no result set at all' { + Mock -ModuleName Maester Get-MtDefenderExploitableVulnerability { return $null } + + $null -eq (Test-MtDefenderExploitableSoftwareVulnerability) | Should -BeTrue + $script:SkippedBecause | Should -Be 'NotApplicable' + } + } + + Context 'Get-MtDefenderSecureConfigurationAssessment' { + It 'normalises the hunting rows and drops rows without a configuration id' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { + @( + [pscustomobject]@{ + ConfigurationId = 'scid-1' + ConfigurationName = 'Name' + ConfigurationDescription = 'Description' + RiskDescription = 'Risk' + ConfigurationCategory = 'OS' + ConfigurationSubcategory = 'Sub' + ConfigurationImpact = 6.5 + ApplicableDeviceCount = 12 + NonCompliantDeviceCount = 3 + NonCompliantDeviceList = @('d1') + }, + [pscustomobject]@{ ConfigurationId = '' } + ) + } + + $result = Get-MtDefenderSecureConfigurationAssessment + $result.Count | Should -Be 1 + $result[0].ConfigurationId | Should -Be 'scid-1' + $result[0].Impact | Should -Be 6.5 + $result[0].NonCompliantDeviceCount | Should -Be 3 + } + + It 'returns an empty list, not null, when the tenant has no assessment' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @() } + + $result = Get-MtDefenderSecureConfigurationAssessment + $null -eq $result | Should -BeFalse + $result.Count | Should -Be 0 + } + } + + Context 'Get-MtDefenderExploitableVulnerability' { + It 'carries the assessed device count as the denominator' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { + @([pscustomobject]@{ + AssessedDeviceCount = 57 + ExposedDeviceCount = 4 + CveCount = 9 + TopDeviceList = @('d1') + TopCveList = @('CVE-2026-0002') + TopSoftwareList = @('Vendor Product') + }) + } + + $summary = Get-MtDefenderExploitableVulnerability + $summary.AssessedDeviceCount | Should -Be 57 + $summary.ExposedDeviceCount | Should -Be 4 + $summary.CveCount | Should -Be 9 + } + + It 'returns null when the query comes back with no row at all' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @() } + + $null -eq (Get-MtDefenderExploitableVulnerability) | Should -BeTrue + } + } +} diff --git a/tests/maester/defender/Test.MT.1255.md b/tests/maester/defender/Test.MT.1255.md new file mode 100644 index 0000000000..df2518624e --- /dev/null +++ b/tests/maester/defender/Test.MT.1255.md @@ -0,0 +1,27 @@ +Ensure no device is left **non-compliant with a Defender Vulnerability Management security recommendation**. + +Defender Vulnerability Management assesses each onboarded device against a catalogue of security configurations — attack surface reduction rules, antivirus settings, firewall state, encryption, account policies and others — and reports, per configuration, which devices comply. An assessor normally reads that one configuration at a time in the Defender portal. This check brings it into a Maester run. + +It runs **once per assessed security configuration**, following the `InstanceSource` pattern `MT.1024` introduced for Entra recommendations. Each configuration becomes its own result, with its own pass or fail. + +A configuration **passes** when every device it applies to complies with it, and **fails** when any applicable device does not. The result carries the configuration's category, its rated impact on the Defender configuration score (1 to 10), the number of applicable and non-compliant devices, the risk description, and up to ten of the non-compliant devices by name. + +Severity follows the source, as #2510 asks: Defender's own rated impact. An impact of 8 or more is reported as High, 4 to 7 as Medium, below 4 as Low. + +Only configurations Defender reports as **applicable to at least one device** are assessed. A configuration that applies to nothing cannot be complied with or breached, so it has no outcome to judge. + +## When this is skipped + +- **No Defender Vulnerability Management data.** When the hunting query returns no assessment, no device is onboarded to Defender for Endpoint or none has reported. The family is skipped with `NoInstances`. A tenant with no onboarded device has no configuration to be compliant with, and is never reported as having none non-compliant. +- **Not licensed.** The check declares `DEFENDER_XDR`, so a tenant without a Defender XDR workload is skipped as not licensed, never failed. + +## How to remediate + +Open the configuration in **Microsoft Defender portal** → **Endpoints** → **Vulnerability management** → **Recommendations**, and either remediate it on the devices listed or accept the risk there, so the recommendation stops being reported. + +## Permissions + +Read-only. This check runs an advanced hunting query through `security/runHuntingQuery` with `ThreatHunting.Read.All`, which is already one of Maester's default Graph scopes. It needs no additional permission. + + +%TestResult% diff --git a/tests/maester/defender/Test.MT.1255.ps1 b/tests/maester/defender/Test.MT.1255.ps1 new file mode 100644 index 0000000000..781e680782 --- /dev/null +++ b/tests/maester/defender/Test.MT.1255.ps1 @@ -0,0 +1,137 @@ +function Get-MtDefenderDeviceSecurityRecommendationInstance { + <# + .SYNOPSIS + Returns one MT.1255 instance per Defender Vulnerability Management security configuration. + + .DESCRIPTION + Instance source of the MT.1255 family. The suffix is the configuration ID + (MT.1255.) and the title names the configuration, so each Defender recommendation + becomes its own row with its own result, the way MT.1024 does for Entra recommendations. + + When Defender returns no assessment at all the source emits nothing and the engine skips the family + with NoInstances. That is deliberate: a tenant with no onboarded device has no configuration to be + compliant with, and must never be reported as having none non-compliant. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + $configurations = Get-MtDefenderSecureConfigurationAssessment + + foreach ($configuration in $configurations) { + # A configuration that applies to no device has no outcome to judge. + if ($configuration.ApplicableDeviceCount -le 0) { continue } + + $name = if ([string]::IsNullOrWhiteSpace($configuration.Name)) { + $configuration.ConfigurationId + } else { + $configuration.Name + } + + [pscustomobject]@{ + Id = $configuration.ConfigurationId + Title = "Every device should comply with the Defender recommendation '$name'." + Data = $configuration + } + } +} + +function Test-MtDefenderDeviceSecurityRecommendation { + <# + .SYNOPSIS + Ensure no device is left non-compliant with a Defender Vulnerability Management security + recommendation. + + .DESCRIPTION + Defender Vulnerability Management assesses each onboarded device against a catalogue of security + configurations and reports, per configuration, which devices comply. An assessor normally reads that + in the Defender portal. This check brings it into a Maester run. + + It runs once per assessed security configuration, following the InstanceSource pattern MT.1024 + introduced. A configuration passes when every device it applies to is compliant with it, and fails + when any applicable device is not. The result names the count and up to ten of the devices, with the + configuration's risk description and its rated impact on the configuration score. + + Only configurations Defender reports as applicable to at least one device are assessed. A tenant + with no Defender Vulnerability Management data is skipped, not passed. + + .OUTPUTS + [bool] - True when every applicable device complies with the configuration, false when any does not, + null when the family is skipped. + + .EXAMPLE + Test-MtDefenderDeviceSecurityRecommendation + + Returns one result per assessed Defender security configuration. + + .LINK + https://maester.dev/docs/commands/Test-MtDefenderDeviceSecurityRecommendation + #> + [MaesterTest( + Id = 'MT.1255', + Title = 'Devices should comply with the Defender Vulnerability Management security recommendations.', + Product = 'defender', + Feature = 'exposure-management', + Area = 'devices', + ResourceType = 'Device', + Severity = 'Medium', + UserImpact = 'Medium', + ImplementationCost = 'Medium', + Mitre = 'None', + Lifecycle = 'Preview', + Service = 'Graph', + License = 'DEFENDER_XDR', + InstanceSource = 'Get-MtDefenderDeviceSecurityRecommendationInstance', + Author = 'earbona23' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # The security configuration to check, supplied by the engine. + $Instance + ) + + $configuration = $Instance.Data + $nonCompliant = [int]$configuration.NonCompliantDeviceCount + $applicable = [int]$configuration.ApplicableDeviceCount + $testResult = $nonCompliant -eq 0 + + # Severity follows the source, as #2510 asks: Defender's own rated impact on the configuration + # score, 1 to 10. + $severity = if ($configuration.Impact -ge 8) { 'High' } elseif ($configuration.Impact -ge 4) { 'Medium' } else { 'Low' } + + $testResultMarkdown = "Defender assesses this configuration on **$applicable** device(s). " + if ($testResult) { + $testResultMarkdown += "All of them comply.`n`n" + } else { + $testResultMarkdown += "**$nonCompliant** of them do not comply.`n`n" + } + + $testResultMarkdown += "| Property | Value |`n| --- | --- |`n" + $testResultMarkdown += "| Configuration ID | ``$($configuration.ConfigurationId)`` |`n" + $testResultMarkdown += "| Category | $($configuration.Category) |`n" + $testResultMarkdown += "| Subcategory | $($configuration.Subcategory) |`n" + $testResultMarkdown += "| Impact on configuration score | $($configuration.Impact) of 10 |`n" + $testResultMarkdown += "| Applicable devices | $applicable |`n" + $testResultMarkdown += "| Non-compliant devices | $nonCompliant |`n" + + if (-not [string]::IsNullOrWhiteSpace($configuration.Description)) { + $testResultMarkdown += "`n$($configuration.Description)`n" + } + + if (-not $testResult) { + if (-not [string]::IsNullOrWhiteSpace($configuration.RiskDescription)) { + $testResultMarkdown += "`n**Risk.** $($configuration.RiskDescription)`n" + } + $devices = @($configuration.NonCompliantDeviceList | Where-Object { $_ }) + if ($devices.Count -gt 0) { + $testResultMarkdown += "`nNon-compliant devices (up to ten shown): $($devices -join ', ')`n" + } + $testResultMarkdown += "`nRemediate the configuration on the devices listed, or accept the risk in the Defender portal so it stops being reported." + } else { + $testResultMarkdown += "`nWell done. Every device this configuration applies to complies with it." + } + + Add-MtTestResultDetail -Result $testResultMarkdown -Severity $severity + return $testResult +} diff --git a/tests/maester/defender/Test.MT.1256.md b/tests/maester/defender/Test.MT.1256.md new file mode 100644 index 0000000000..57178731a0 --- /dev/null +++ b/tests/maester/defender/Test.MT.1256.md @@ -0,0 +1,27 @@ +Ensure no device runs **software with a high or critical vulnerability for which exploit code is publicly available**. + +Defender Vulnerability Management knows two things separately: which vulnerabilities are present on each onboarded device, and — from its vulnerability knowledge base — whether exploit code for a given vulnerability is publicly available. The intersection of the two is the part of the fleet an attacker can act on today with code they do not have to write. + +This check **fails** when any onboarded device runs software with a high or critical vulnerability whose exploit code is publicly available, and reports how many devices are exposed, across how many distinct CVEs, with up to ten CVEs, software products and device names. + +## On the signal used + +The issue that asked for this check names the **CISA Known Exploited Vulnerabilities** catalogue. The advanced hunting schema exposes no CISA KEV flag: `DeviceTvmSoftwareVulnerabilitiesKB` carries `CveId`, `CvssScore`, `IsExploitAvailable`, `VulnerabilitySeverityLevel`, `LastModifiedTime`, `PublishedDate`, `VulnerabilityDescription` and `AffectedSoftware`, and nothing else. + +`IsExploitAvailable`, documented by Microsoft as *"whether exploit code for the vulnerability is publicly available"*, is the closest first-party signal, and it is what this check reports. **It does not claim CISA KEV membership.** The two sets overlap heavily but are not the same, and reporting one as the other would put a claim in the result that the data does not support. + +## When this is skipped + +- **Nothing assessed.** The check carries the number of distinct devices Defender has any vulnerability data for as a denominator. When that is zero, no device is onboarded to Defender for Endpoint or none has reported, and the result is skipped as not applicable. **Zero exposed devices out of zero assessed devices is not a pass.** +- **Not licensed.** The check declares `DEFENDER_XDR`, so a tenant without a Defender XDR workload is skipped as not licensed, never failed. + +## How to remediate + +Patch or remove the software listed. Exploit code for these vulnerabilities is already public, so the window between disclosure and attack has closed. Work the list in **Microsoft Defender portal** → **Endpoints** → **Vulnerability management** → **Weaknesses**, filtered on exploit availability. + +## Permissions + +Read-only. This check runs an advanced hunting query through `security/runHuntingQuery` with `ThreatHunting.Read.All`, which is already one of Maester's default Graph scopes. It needs no additional permission. + + +%TestResult% diff --git a/tests/maester/defender/Test.MT.1256.ps1 b/tests/maester/defender/Test.MT.1256.ps1 new file mode 100644 index 0000000000..3d4852c78c --- /dev/null +++ b/tests/maester/defender/Test.MT.1256.ps1 @@ -0,0 +1,103 @@ +function Test-MtDefenderExploitableSoftwareVulnerability { + <# + .SYNOPSIS + Ensure no device runs software with a high or critical vulnerability for which exploit code is + publicly available. + + .DESCRIPTION + Defender Vulnerability Management knows both the vulnerabilities present on each device and, from + its vulnerability knowledge base, whether exploit code for a vulnerability is publicly available. + The intersection is the part of the fleet an attacker can act on today with code they do not have to + write. + + This check fails when any onboarded device runs software with a high or critical vulnerability whose + IsExploitAvailable is true in DeviceTvmSoftwareVulnerabilitiesKB. + + On the signal used: the advanced hunting schema exposes no CISA KEV flag. IsExploitAvailable, + documented as "whether exploit code for the vulnerability is publicly available", is the closest + first-party signal, and it is what this check reports. It does not claim CISA KEV membership. + + The check does not pass on an unassessed fleet. It carries the number of distinct devices Defender + has any vulnerability data for as a denominator; when that is zero, no device is onboarded to + Defender for Endpoint or none has reported, and the result is skipped as not applicable. Zero + exposed devices out of zero assessed devices is not a pass. + + .OUTPUTS + [bool] - True when no assessed device is exposed, false when any is, null when skipped. + + .EXAMPLE + Test-MtDefenderExploitableSoftwareVulnerability + + Returns true if no assessed device runs software with a publicly exploitable high or critical + vulnerability. + + .LINK + https://maester.dev/docs/commands/Test-MtDefenderExploitableSoftwareVulnerability + #> + [MaesterTest( + Id = 'MT.1256', + Title = 'Devices should not run software with a publicly exploitable high or critical vulnerability.', + Product = 'defender', + Feature = 'exposure-management', + Area = 'devices', + ResourceType = 'Device', + Severity = 'High', + UserImpact = 'Medium', + ImplementationCost = 'Medium', + Mitre = 'T1190', + Lifecycle = 'Preview', + Service = 'Graph', + License = 'DEFENDER_XDR', + Author = 'earbona23' + )] + [CmdletBinding()] + [OutputType([bool])] + param() + + $summary = Get-MtDefenderExploitableVulnerability + if ($null -eq $summary) { + # Defender returned no result set at all. Report a skip rather than a clean fleet. + Add-MtTestResultDetail -SkippedBecause NotApplicable + return $null + } + + if ($summary.AssessedDeviceCount -le 0) { + # No device has any vulnerability data, so there is no fleet to judge. Zero exposed out of zero + # assessed is not a pass. + Add-MtTestResultDetail -SkippedBecause NotApplicable + return $null + } + + $testResult = $summary.ExposedDeviceCount -eq 0 + $share = [math]::Round(($summary.ExposedDeviceCount / $summary.AssessedDeviceCount) * 100, 1) + + $testResultMarkdown = "Defender Vulnerability Management has data for **$($summary.AssessedDeviceCount)** device(s). " + if ($testResult) { + $testResultMarkdown += "None of them runs software with a publicly exploitable high or critical vulnerability.`n`n" + $testResultMarkdown += "Well done. There is nothing an attacker can act on with published exploit code on this fleet today." + } else { + $testResultMarkdown += "**$($summary.ExposedDeviceCount)** of them ($share%) run software with a publicly exploitable high or critical vulnerability, across **$($summary.CveCount)** distinct CVE(s).`n`n" + $testResultMarkdown += "| Property | Value |`n| --- | --- |`n" + $testResultMarkdown += "| Assessed devices | $($summary.AssessedDeviceCount) |`n" + $testResultMarkdown += "| Exposed devices | $($summary.ExposedDeviceCount) |`n" + $testResultMarkdown += "| Distinct CVEs | $($summary.CveCount) |`n" + + $cve = @($summary.TopCveList | Where-Object { $_ }) + if ($cve.Count -gt 0) { + $testResultMarkdown += "`nCVEs (up to ten shown): $($cve -join ', ')`n" + } + $software = @($summary.TopSoftwareList | Where-Object { $_ }) + if ($software.Count -gt 0) { + $testResultMarkdown += "`nSoftware (up to ten shown): $($software -join ', ')`n" + } + $devices = @($summary.TopDeviceList | Where-Object { $_ }) + if ($devices.Count -gt 0) { + $testResultMarkdown += "`nDevices (up to ten shown): $($devices -join ', ')`n" + } + + $testResultMarkdown += "`nPatch or remove the software listed. Exploit code for these vulnerabilities is already public, so the window between disclosure and attack has closed." + } + + Add-MtTestResultDetail -Result $testResultMarkdown + return $testResult +} From 1fb5b5c909cf5bb558d783e2ea6f42131537c52d Mon Sep 17 00:00:00 2001 From: Eduard Arbona Date: Fri, 6 Nov 2026 22:12:17 -0400 Subject: [PATCH 02/14] fix(MT.1255): the per-instance severity goes on the instance The family computed a severity from Defender's rated impact and passed it to Add-MtTestResultDetail, where the engine never reads it: Invoke-MtNativePlan resolves severity as config row, then the instance, then the attribute, then the detail, and the test declares Severity in the attribute. So every row reported the attribute's Medium and the claim that severity follows the source was not true of the output. The severity now goes on the instance object, which is second in that order and is what MT.1024 and MT.1059 already do. No other behaviour changes. The unit test that covered the impact mapping asserted it on the mocked detail, so it passed while the engine discarded the value. It now drives the instance source, and a second test asserts that nothing is passed to Add-MtTestResultDetail. --- ...tDefenderVulnerabilityManagement.Tests.ps1 | 19 ++++++++++++++---- tests/maester/defender/Test.MT.1255.ps1 | 20 +++++++++++-------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 index 6fa0f1b61a..fbeb1207b1 100644 --- a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 @@ -81,7 +81,10 @@ Describe 'Defender Vulnerability Management device recommendations and exploitab $script:TestResult | Should -Match 'Non-compliant devices \(up to ten shown\): a, b' } - It 'takes the severity from the impact Defender reports' { + # 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 mocked detail is what let this ship the wrong way round. + It 'takes the severity from the impact Defender reports, on the instance the engine reads' { foreach ($case in @( @{ Impact = 9; Expected = 'High' }, @{ Impact = 8; Expected = 'High' }, @@ -90,12 +93,20 @@ Describe 'Defender Vulnerability Management device recommendations and exploitab @{ Impact = 3; Expected = 'Low' }, @{ Impact = 1; Expected = 'Low' } )) { - $instance = [pscustomobject]@{ Data = Get-TestConfiguration -Impact $case.Impact } - $null = Test-MtDefenderDeviceSecurityRecommendation -Instance $instance - $script:Severity | Should -Be $case.Expected -Because "an impact of $($case.Impact) maps to $($case.Expected)" + Mock -ModuleName Maester Get-MtDefenderSecureConfigurationAssessment { @(Get-TestConfiguration -Impact $case.Impact) } + + $instance = @(Get-MtDefenderDeviceSecurityRecommendationInstance)[0] + $instance.Severity | Should -Be $case.Expected -Because "an impact of $($case.Impact) maps to $($case.Expected)" } } + It 'passes no severity to Add-MtTestResultDetail, which the attribute would discard' { + $instance = [pscustomobject]@{ Data = Get-TestConfiguration -Impact 9 } + + $null = Test-MtDefenderDeviceSecurityRecommendation -Instance $instance + $script:Severity | Should -BeNullOrEmpty + } + It 'reports the risk description only when the configuration fails' { $passing = [pscustomobject]@{ Data = Get-TestConfiguration -NonCompliant 0 } $null = Test-MtDefenderDeviceSecurityRecommendation -Instance $passing diff --git a/tests/maester/defender/Test.MT.1255.ps1 b/tests/maester/defender/Test.MT.1255.ps1 index 781e680782..30d2b82700 100644 --- a/tests/maester/defender/Test.MT.1255.ps1 +++ b/tests/maester/defender/Test.MT.1255.ps1 @@ -28,10 +28,18 @@ function Get-MtDefenderDeviceSecurityRecommendationInstance { $configuration.Name } + # Severity follows the source, as #2510 asks: Defender's own rated impact on the configuration + # score, 1 to 10. 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. + $severity = if ($configuration.Impact -ge 8) { 'High' } elseif ($configuration.Impact -ge 4) { 'Medium' } else { 'Low' } + [pscustomobject]@{ - Id = $configuration.ConfigurationId - Title = "Every device should comply with the Defender recommendation '$name'." - Data = $configuration + Id = $configuration.ConfigurationId + Title = "Every device should comply with the Defender recommendation '$name'." + Severity = $severity + Data = $configuration } } } @@ -96,10 +104,6 @@ function Test-MtDefenderDeviceSecurityRecommendation { $applicable = [int]$configuration.ApplicableDeviceCount $testResult = $nonCompliant -eq 0 - # Severity follows the source, as #2510 asks: Defender's own rated impact on the configuration - # score, 1 to 10. - $severity = if ($configuration.Impact -ge 8) { 'High' } elseif ($configuration.Impact -ge 4) { 'Medium' } else { 'Low' } - $testResultMarkdown = "Defender assesses this configuration on **$applicable** device(s). " if ($testResult) { $testResultMarkdown += "All of them comply.`n`n" @@ -132,6 +136,6 @@ function Test-MtDefenderDeviceSecurityRecommendation { $testResultMarkdown += "`nWell done. Every device this configuration applies to complies with it." } - Add-MtTestResultDetail -Result $testResultMarkdown -Severity $severity + Add-MtTestResultDetail -Result $testResultMarkdown return $testResult } From 2ef6908fe9bb31418e25e94216a8d299dfbeb370 Mon Sep 17 00:00:00 2001 From: Eduard Arbona Date: Fri, 6 Nov 2026 23:23:41 -0400 Subject: [PATCH 03/14] fix(MT.1256): Severity is Medium, not High The test reads IsExploitAvailable and nothing else: it has no internet-exposure or remote-exploitability condition, so many of its failures need local access or a prior foothold. MT.1087, which does require public exposure and remote exploitability, is the one rated High. With two levels fitting, the rubric takes the lower. Raised by the attribute review. --- tests/maester/defender/Test.MT.1256.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/maester/defender/Test.MT.1256.ps1 b/tests/maester/defender/Test.MT.1256.ps1 index 3d4852c78c..62cda576aa 100644 --- a/tests/maester/defender/Test.MT.1256.ps1 +++ b/tests/maester/defender/Test.MT.1256.ps1 @@ -41,7 +41,7 @@ function Test-MtDefenderExploitableSoftwareVulnerability { Feature = 'exposure-management', Area = 'devices', ResourceType = 'Device', - Severity = 'High', + Severity = 'Medium', UserImpact = 'Medium', ImplementationCost = 'Medium', Mitre = 'T1190', From 0b028cb7da307aa6d126fa03c54ee25e2372e671 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:53:29 -0400 Subject: [PATCH 04/14] fix(MT.1255): no severity when the knowledge base publishes no impact MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The knowledge base join is a leftouter, so a configuration can come back with no impact at all. `[double]$null` is 0, so the instance was given `Low` — and the instance wins over the attribute, so a FAILING configuration was reported as the lowest severity there is, with nothing in the output saying the source had not rated it. Three changes, one per layer: - the helper returns `$null` instead of 0 when the knowledge base has no row, so it stops inventing "impact 1 of 10, the lowest" where it means "not known"; - the instance leaves `Severity` unset in that case. The engine's precedence is config, then instance, then attribute, and it tests the instance value for truthiness (Invoke-MtNativePlan.ps1:467-470), so `$null` falls through to the attribute's Medium; - the result table says "not published by the knowledge base" rather than rendering " of 10" with nothing in front of it. The fixture's `-Impact` becomes `[object]` so a test can pass `$null`: a missing impact is a real shape from that join, not an invalid one. Verified both ways: 18 of 18 with the fix, and with the two source files reverted the new case is the only one that fails. --- ...MtDefenderSecureConfigurationAssessment.ps1 | 7 +++++-- ...MtDefenderVulnerabilityManagement.Tests.ps1 | 18 ++++++++++++++++-- tests/maester/defender/Test.MT.1255.ps1 | 14 +++++++++++--- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/powershell/internal/services/defender/Get-MtDefenderSecureConfigurationAssessment.ps1 b/powershell/internal/services/defender/Get-MtDefenderSecureConfigurationAssessment.ps1 index fa9c64568c..dbc2e364fc 100644 --- a/powershell/internal/services/defender/Get-MtDefenderSecureConfigurationAssessment.ps1 +++ b/powershell/internal/services/defender/Get-MtDefenderSecureConfigurationAssessment.ps1 @@ -1,4 +1,4 @@ -function Get-MtDefenderSecureConfigurationAssessment { +function Get-MtDefenderSecureConfigurationAssessment { <# .SYNOPSIS Returns one row per Defender Vulnerability Management security configuration, with how many devices @@ -62,7 +62,10 @@ DeviceTvmSecureConfigurationAssessment RiskDescription = [string]$row.RiskDescription Category = [string]$row.ConfigurationCategory Subcategory = [string]$row.ConfigurationSubcategory - Impact = [double]($row.ConfigurationImpact) + # $null, not 0, when the knowledge base has no row for this configuration: the join + # above is a leftouter, and [double]$null is 0, which reads as "impact 1 to 10, the + # lowest" rather than "not known". The caller decides what to do with the absence. + Impact = if ($null -eq $row.ConfigurationImpact -or [string]::IsNullOrWhiteSpace([string]$row.ConfigurationImpact)) { $null } else { [double]$row.ConfigurationImpact } ApplicableDeviceCount = [int]($row.ApplicableDeviceCount) NonCompliantDeviceCount = [int]($row.NonCompliantDeviceCount) NonCompliantDeviceList = @($row.NonCompliantDeviceList) diff --git a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 index fbeb1207b1..232195886f 100644 --- a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 @@ -1,4 +1,4 @@ -Describe 'Defender Vulnerability Management device recommendations and exploitable vulnerabilities' { +Describe 'Defender Vulnerability Management device recommendations and exploitable vulnerabilities' { BeforeAll { Import-Module $PSScriptRoot/../../Maester.psd1 -Force . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" @@ -14,7 +14,9 @@ Describe 'Defender Vulnerability Management device recommendations and exploitab [string] $Name = 'Enable Microsoft Defender Antivirus', [int] $Applicable = 10, [int] $NonCompliant = 0, - [double] $Impact = 5, + # [object], not [double], so a test can pass $null: the knowledge base join is a + # leftouter and a missing impact is a real shape, not an invalid one. + [AllowNull()] [object] $Impact = 5, [string[]] $NonCompliantDevices = @() ) return [pscustomobject]@{ @@ -100,6 +102,18 @@ Describe 'Defender Vulnerability Management device recommendations and exploitab } } + It 'leaves Severity unset when the knowledge base publishes no impact' { + # The knowledge base join is a leftouter, so a configuration can come back with no + # impact at all. Deriving a severity from that reported a FAILING configuration as + # Low, because [double]$null is 0. Unset lets the engine fall through to the + # attribute's Medium (Invoke-MtNativePlan.ps1:467-470 tests the instance value for + # truthiness), which is the honest answer when the source does not say. + Mock -ModuleName Maester Get-MtDefenderSecureConfigurationAssessment { @(Get-TestConfiguration -Impact $null) } + + $instance = @(Get-MtDefenderDeviceSecurityRecommendationInstance)[0] + $instance.Severity | Should -BeNullOrEmpty + } + It 'passes no severity to Add-MtTestResultDetail, which the attribute would discard' { $instance = [pscustomobject]@{ Data = Get-TestConfiguration -Impact 9 } diff --git a/tests/maester/defender/Test.MT.1255.ps1 b/tests/maester/defender/Test.MT.1255.ps1 index 30d2b82700..055cad86ce 100644 --- a/tests/maester/defender/Test.MT.1255.ps1 +++ b/tests/maester/defender/Test.MT.1255.ps1 @@ -1,4 +1,4 @@ -function Get-MtDefenderDeviceSecurityRecommendationInstance { +function Get-MtDefenderDeviceSecurityRecommendationInstance { <# .SYNOPSIS Returns one MT.1255 instance per Defender Vulnerability Management security configuration. @@ -33,7 +33,14 @@ function Get-MtDefenderDeviceSecurityRecommendationInstance { # 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. - $severity = if ($configuration.Impact -ge 8) { 'High' } elseif ($configuration.Impact -ge 4) { 'Medium' } else { 'Low' } + # Left unset when the knowledge base has no impact for this configuration. The engine's + # precedence is config, then instance, then attribute (Invoke-MtNativePlan.ps1:467-470) and + # it tests the instance value for truthiness, so $null falls through to the attribute's + # Medium. Deriving it from a missing impact would report a failing configuration as Low. + $severity = if ($null -eq $configuration.Impact) { $null } + elseif ($configuration.Impact -ge 8) { 'High' } + elseif ($configuration.Impact -ge 4) { 'Medium' } + else { 'Low' } [pscustomobject]@{ Id = $configuration.ConfigurationId @@ -115,7 +122,8 @@ function Test-MtDefenderDeviceSecurityRecommendation { $testResultMarkdown += "| Configuration ID | ``$($configuration.ConfigurationId)`` |`n" $testResultMarkdown += "| Category | $($configuration.Category) |`n" $testResultMarkdown += "| Subcategory | $($configuration.Subcategory) |`n" - $testResultMarkdown += "| Impact on configuration score | $($configuration.Impact) of 10 |`n" + $impactoTexto = if ($null -eq $configuration.Impact) { 'not published by the knowledge base' } else { "$($configuration.Impact) of 10" } + $testResultMarkdown += "| Impact on configuration score | $impactoTexto |`n" $testResultMarkdown += "| Applicable devices | $applicable |`n" $testResultMarkdown += "| Non-compliant devices | $nonCompliant |`n" From cd60ccbe593c47732f22f3f54eaf13b306ba1096 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Sat, 7 Nov 2026 17:07:07 -0400 Subject: [PATCH 05/14] chore: save the new PowerShell files as UTF-8 with BOM Per the ruling on #2663: every .ps1, .psm1 and .psd1 is UTF-8 with a byte order mark. These files were written without one, so they would fail the check #2714 adds once it lands. Only the three bytes EF BB BF are prepended; nothing else in the files changes. --- .../defender/Get-MtDefenderExploitableVulnerability.ps1 | 2 +- tests/maester/defender/Test.MT.1256.ps1 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/powershell/internal/services/defender/Get-MtDefenderExploitableVulnerability.ps1 b/powershell/internal/services/defender/Get-MtDefenderExploitableVulnerability.ps1 index 83640d92c1..2bd6ddc4a6 100644 --- a/powershell/internal/services/defender/Get-MtDefenderExploitableVulnerability.ps1 +++ b/powershell/internal/services/defender/Get-MtDefenderExploitableVulnerability.ps1 @@ -1,4 +1,4 @@ -function Get-MtDefenderExploitableVulnerability { +function Get-MtDefenderExploitableVulnerability { <# .SYNOPSIS Returns a single summary of the devices that run software with a high or critical vulnerability for diff --git a/tests/maester/defender/Test.MT.1256.ps1 b/tests/maester/defender/Test.MT.1256.ps1 index 62cda576aa..68b979bb13 100644 --- a/tests/maester/defender/Test.MT.1256.ps1 +++ b/tests/maester/defender/Test.MT.1256.ps1 @@ -1,4 +1,4 @@ -function Test-MtDefenderExploitableSoftwareVulnerability { +function Test-MtDefenderExploitableSoftwareVulnerability { <# .SYNOPSIS Ensure no device runs software with a high or critical vulnerability for which exploit code is From 2931d26381f61e0d90f6fdee1be7cc798b9dfe8e Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:40:22 -0400 Subject: [PATCH 06/14] chore: renumber to the next free MT sequence (MT.1255/1256 -> MT.1269/1270) MT.1253-1258 are already reserved by Cloud-Architekt on #697 (28 Oct) and used in #2705, so this PR had taken numbers that were not free. Renumbered from MT.1267, the next free number after MT.1266, and reserved the new range on #697. The golden selection fixture was regenerated with build/golden/Export-MtGoldenFixture.ps1 rather than edited by hand, as the file itself asks. --- powershell/tests/fixtures/golden/selection.json | 12 ++++++------ .../Test-MtDefenderVulnerabilityManagement.Tests.ps1 | 6 +++--- .../defender/{Test.MT.1255.md => Test.MT.1269.md} | 0 .../defender/{Test.MT.1255.ps1 => Test.MT.1269.ps1} | 8 ++++---- .../defender/{Test.MT.1256.md => Test.MT.1270.md} | 0 .../defender/{Test.MT.1256.ps1 => Test.MT.1270.ps1} | 2 +- 6 files changed, 14 insertions(+), 14 deletions(-) rename tests/maester/defender/{Test.MT.1255.md => Test.MT.1269.md} (100%) rename tests/maester/defender/{Test.MT.1255.ps1 => Test.MT.1269.ps1} (96%) rename tests/maester/defender/{Test.MT.1256.md => Test.MT.1270.md} (100%) rename tests/maester/defender/{Test.MT.1256.ps1 => Test.MT.1270.ps1} (99%) diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index 6be70c085e..b70c865ebc 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -2448,11 +2448,11 @@ "MT.1250", "MT.1251", "MT.1252", - "MT.1255", - "MT.1256", "MT.1259", "MT.1260", "MT.1265", + "MT.1269", + "MT.1270", "ORCA.100", "ORCA.101", "ORCA.102", @@ -3093,11 +3093,11 @@ "MT.1250", "MT.1251", "MT.1252", - "MT.1255", - "MT.1256", "MT.1259", "MT.1260", "MT.1265", + "MT.1269", + "MT.1270", "ORCA.100", "ORCA.101", "ORCA.102", @@ -4447,11 +4447,11 @@ "MT.1250", "MT.1251", "MT.1252", - "MT.1255", - "MT.1256", "MT.1259", "MT.1260", "MT.1265", + "MT.1269", + "MT.1270", "ORCA.100", "ORCA.101", "ORCA.102", diff --git a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 index 232195886f..1afe80c08c 100644 --- a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 @@ -65,7 +65,7 @@ } } - Context 'Test-MtDefenderDeviceSecurityRecommendation (MT.1255)' { + Context 'Test-MtDefenderDeviceSecurityRecommendation (MT.1269)' { It 'passes when every applicable device complies' { $instance = [pscustomobject]@{ Data = Get-TestConfiguration -Applicable 25 -NonCompliant 0 } @@ -132,7 +132,7 @@ } } - Context 'Get-MtDefenderDeviceSecurityRecommendationInstance (MT.1255 instance source)' { + Context 'Get-MtDefenderDeviceSecurityRecommendationInstance (MT.1269 instance source)' { It 'emits one instance per assessed configuration' { Mock -ModuleName Maester Get-MtDefenderSecureConfigurationAssessment { @(Get-TestConfiguration -Name 'One'), @(Get-TestConfiguration -Name 'Two') @@ -169,7 +169,7 @@ } } - Context 'Test-MtDefenderExploitableSoftwareVulnerability (MT.1256)' { + Context 'Test-MtDefenderExploitableSoftwareVulnerability (MT.1270)' { It 'passes when no assessed device is exposed' { Mock -ModuleName Maester Get-MtDefenderExploitableVulnerability { Get-TestVulnerabilitySummary -Assessed 100 -Exposed 0 diff --git a/tests/maester/defender/Test.MT.1255.md b/tests/maester/defender/Test.MT.1269.md similarity index 100% rename from tests/maester/defender/Test.MT.1255.md rename to tests/maester/defender/Test.MT.1269.md diff --git a/tests/maester/defender/Test.MT.1255.ps1 b/tests/maester/defender/Test.MT.1269.ps1 similarity index 96% rename from tests/maester/defender/Test.MT.1255.ps1 rename to tests/maester/defender/Test.MT.1269.ps1 index 055cad86ce..bea0d57f1c 100644 --- a/tests/maester/defender/Test.MT.1255.ps1 +++ b/tests/maester/defender/Test.MT.1269.ps1 @@ -1,11 +1,11 @@ function Get-MtDefenderDeviceSecurityRecommendationInstance { <# .SYNOPSIS - Returns one MT.1255 instance per Defender Vulnerability Management security configuration. + Returns one MT.1269 instance per Defender Vulnerability Management security configuration. .DESCRIPTION - Instance source of the MT.1255 family. The suffix is the configuration ID - (MT.1255.) and the title names the configuration, so each Defender recommendation + Instance source of the MT.1269 family. The suffix is the configuration ID + (MT.1269.) and the title names the configuration, so each Defender recommendation becomes its own row with its own result, the way MT.1024 does for Entra recommendations. When Defender returns no assessment at all the source emits nothing and the engine skips the family @@ -83,7 +83,7 @@ function Test-MtDefenderDeviceSecurityRecommendation { https://maester.dev/docs/commands/Test-MtDefenderDeviceSecurityRecommendation #> [MaesterTest( - Id = 'MT.1255', + Id = 'MT.1269', Title = 'Devices should comply with the Defender Vulnerability Management security recommendations.', Product = 'defender', Feature = 'exposure-management', diff --git a/tests/maester/defender/Test.MT.1256.md b/tests/maester/defender/Test.MT.1270.md similarity index 100% rename from tests/maester/defender/Test.MT.1256.md rename to tests/maester/defender/Test.MT.1270.md diff --git a/tests/maester/defender/Test.MT.1256.ps1 b/tests/maester/defender/Test.MT.1270.ps1 similarity index 99% rename from tests/maester/defender/Test.MT.1256.ps1 rename to tests/maester/defender/Test.MT.1270.ps1 index 68b979bb13..d79fe013bd 100644 --- a/tests/maester/defender/Test.MT.1256.ps1 +++ b/tests/maester/defender/Test.MT.1270.ps1 @@ -35,7 +35,7 @@ https://maester.dev/docs/commands/Test-MtDefenderExploitableSoftwareVulnerability #> [MaesterTest( - Id = 'MT.1256', + Id = 'MT.1270', Title = 'Devices should not run software with a publicly exploitable high or critical vulnerability.', Product = 'defender', Feature = 'exposure-management', From c79196938d80dce8fdc9dd95d84d30f4beae592c Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Sun, 8 Nov 2026 10:15:01 -0400 Subject: [PATCH 07/14] fix(defender): drop the unsupported MITRE mapping and escape tenant names Two findings from @coderabbitai on this PR, plus the sibling it did not reach. MT.1270 declared Mitre = 'T1190'. That technique is about exploiting a public-facing application, and this check only establishes that software with a publicly exploitable vulnerability is installed - never that anything is reachable from outside. On a fleet of internal or client software the mapping is simply wrong, so it is now 'None', which is what 328 other tests use when the evidence does not pin a technique. Software names come from the tenant's inventory and were interpolated straight into Markdown, so a name carrying link syntax would render as a link in the report. They now go through Get-MtSafeMarkdown. The same applies to device names, which are tenant-controlled as well: in MT.1270 and, for the same reason, in MT.1269, which the review did not flag. Fixing only the line that was reported would have left the identical defect two files away. --- tests/maester/defender/Test.MT.1269.ps1 | 5 ++++- tests/maester/defender/Test.MT.1270.ps1 | 15 ++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/tests/maester/defender/Test.MT.1269.ps1 b/tests/maester/defender/Test.MT.1269.ps1 index bea0d57f1c..aaf9f7ae48 100644 --- a/tests/maester/defender/Test.MT.1269.ps1 +++ b/tests/maester/defender/Test.MT.1269.ps1 @@ -137,7 +137,10 @@ function Test-MtDefenderDeviceSecurityRecommendation { } $devices = @($configuration.NonCompliantDeviceList | Where-Object { $_ }) if ($devices.Count -gt 0) { - $testResultMarkdown += "`nNon-compliant devices (up to ten shown): $($devices -join ', ')`n" + # Device names are tenant-controlled, so they are escaped before reaching Markdown. + # Same class as the finding @coderabbitai raised on MT.1270 in this PR. + $safeDevices = @($devices | ForEach-Object { Get-MtSafeMarkdown $_ }) + $testResultMarkdown += "`nNon-compliant devices (up to ten shown): $($safeDevices -join ', ')`n" } $testResultMarkdown += "`nRemediate the configuration on the devices listed, or accept the risk in the Defender portal so it stops being reported." } else { diff --git a/tests/maester/defender/Test.MT.1270.ps1 b/tests/maester/defender/Test.MT.1270.ps1 index d79fe013bd..e37333a938 100644 --- a/tests/maester/defender/Test.MT.1270.ps1 +++ b/tests/maester/defender/Test.MT.1270.ps1 @@ -44,7 +44,11 @@ Severity = 'Medium', UserImpact = 'Medium', ImplementationCost = 'Medium', - Mitre = 'T1190', + # Not T1190: that technique is about exploiting a public-facing application, and this + # check only establishes that vulnerable software is installed, never that it is + # reachable from outside. Mapping it would misclassify a fleet of internal or client + # software. Reported by @coderabbitai on #2695. + Mitre = 'None', Lifecycle = 'Preview', Service = 'Graph', License = 'DEFENDER_XDR', @@ -88,11 +92,16 @@ } $software = @($summary.TopSoftwareList | Where-Object { $_ }) if ($software.Count -gt 0) { - $testResultMarkdown += "`nSoftware (up to ten shown): $($software -join ', ')`n" + # Software names come from the tenant's inventory, so they are escaped before they + # reach Markdown: a name carrying link syntax would otherwise render as a link. + $safeSoftware = @($software | ForEach-Object { Get-MtSafeMarkdown $_ }) + $testResultMarkdown += "`nSoftware (up to ten shown): $($safeSoftware -join ', ')`n" } $devices = @($summary.TopDeviceList | Where-Object { $_ }) if ($devices.Count -gt 0) { - $testResultMarkdown += "`nDevices (up to ten shown): $($devices -join ', ')`n" + # Device names are tenant-controlled too. + $safeDevices = @($devices | ForEach-Object { Get-MtSafeMarkdown $_ }) + $testResultMarkdown += "`nDevices (up to ten shown): $($safeDevices -join ', ')`n" } $testResultMarkdown += "`nPatch or remove the software listed. Exploit code for these vulnerabilities is already public, so the window between disclosure and attack has closed." From 5997ad8422cb73842132908096ea54b9727998f1 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Sun, 8 Nov 2026 10:23:50 -0400 Subject: [PATCH 08/14] fix(defender): T1203 for MT.1270, escape the KB text, and compare with MT.1087 Picking up the rest of @merill's review. The attribute review rejected 'None' as well, and it is right: the description names attacker behaviour, so the rubric wants a technique. Of the three it offered - T1203, T1068, T1210 - T1203 is what patching vulnerable endpoint software actually prevents. T1190 was wrong for the opposite reason: it needs a public-facing application, which this check never establishes. The knowledge base description and risk text in MT.1269 now go through Get-MtSafeMarkdown, like the device and software names. The MT.1270 guide now says how it differs from MT.1087: MT.1087 requires the device to be internet exposed and the vulnerability to be remotely exploitable, which is why it is High; this one has neither condition and is Medium. A tenant can pass MT.1087 and fail this, and that is the intended reading. --- tests/maester/defender/Test.MT.1269.ps1 | 6 ++++-- tests/maester/defender/Test.MT.1270.md | 17 +++++++++++++++++ tests/maester/defender/Test.MT.1270.ps1 | 9 +++++---- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/tests/maester/defender/Test.MT.1269.ps1 b/tests/maester/defender/Test.MT.1269.ps1 index aaf9f7ae48..8b7feab7ac 100644 --- a/tests/maester/defender/Test.MT.1269.ps1 +++ b/tests/maester/defender/Test.MT.1269.ps1 @@ -128,12 +128,14 @@ function Test-MtDefenderDeviceSecurityRecommendation { $testResultMarkdown += "| Non-compliant devices | $nonCompliant |`n" if (-not [string]::IsNullOrWhiteSpace($configuration.Description)) { - $testResultMarkdown += "`n$($configuration.Description)`n" + # The knowledge base text is rendered as Markdown, so it is escaped like any other + # value the report does not author itself. + $testResultMarkdown += "`n$(Get-MtSafeMarkdown $configuration.Description)`n" } if (-not $testResult) { if (-not [string]::IsNullOrWhiteSpace($configuration.RiskDescription)) { - $testResultMarkdown += "`n**Risk.** $($configuration.RiskDescription)`n" + $testResultMarkdown += "`n**Risk.** $(Get-MtSafeMarkdown $configuration.RiskDescription)`n" } $devices = @($configuration.NonCompliantDeviceList | Where-Object { $_ }) if ($devices.Count -gt 0) { diff --git a/tests/maester/defender/Test.MT.1270.md b/tests/maester/defender/Test.MT.1270.md index 57178731a0..ea81cfce46 100644 --- a/tests/maester/defender/Test.MT.1270.md +++ b/tests/maester/defender/Test.MT.1270.md @@ -10,6 +10,23 @@ The issue that asked for this check names the **CISA Known Exploited Vulnerabili `IsExploitAvailable`, documented by Microsoft as *"whether exploit code for the vulnerability is publicly available"*, is the closest first-party signal, and it is what this check reports. **It does not claim CISA KEV membership.** The two sets overlap heavily but are not the same, and reporting one as the other would put a claim in the result that the data does not support. +## How this differs from MT.1087 + +`MT.1087` and this check look at the same vulnerability data and are deliberately not the same test. + +| | MT.1087 | MT.1270 | +| --- | --- | --- | +| Device must be internet exposed | **Yes** - incoming connections from public IP addresses in the last 7 days | No | +| Vulnerability must be remotely exploitable over the network | **Yes** | No | +| Exploit code publicly available | Yes | Yes | +| Severity | `High` | `Medium` | + +MT.1087 answers *which devices can be reached and attacked from the internet right now*, which is why it +is rated higher. This check answers the broader question: *where in the fleet is software an attacker +could exploit with code they do not have to write* - including devices that are not exposed, and +vulnerabilities that need local access. A tenant can pass MT.1087 and still fail this one, and that is +the intended reading, not a contradiction. + ## When this is skipped - **Nothing assessed.** The check carries the number of distinct devices Defender has any vulnerability data for as a denominator. When that is zero, no device is onboarded to Defender for Endpoint or none has reported, and the result is skipped as not applicable. **Zero exposed devices out of zero assessed devices is not a pass.** diff --git a/tests/maester/defender/Test.MT.1270.ps1 b/tests/maester/defender/Test.MT.1270.ps1 index e37333a938..23f69135d3 100644 --- a/tests/maester/defender/Test.MT.1270.ps1 +++ b/tests/maester/defender/Test.MT.1270.ps1 @@ -45,10 +45,11 @@ UserImpact = 'Medium', ImplementationCost = 'Medium', # Not T1190: that technique is about exploiting a public-facing application, and this - # check only establishes that vulnerable software is installed, never that it is - # reachable from outside. Mapping it would misclassify a fleet of internal or client - # software. Reported by @coderabbitai on #2695. - Mitre = 'None', + # check never establishes that anything is reachable from outside, so it would + # misclassify a fleet of internal or client software. T1203 is what patching this + # software actually prevents on an endpoint. `None` was wrong too: the attribute + # review reads the description as naming attacker behaviour, which it does. + Mitre = 'T1203', Lifecycle = 'Preview', Service = 'Graph', License = 'DEFENDER_XDR', From a9998863dc18df3fdc62acf7486ac127132a8982 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Sun, 8 Nov 2026 10:51:19 -0400 Subject: [PATCH 09/14] fix: move the Mitre note above the attribute and keep the canonical order The migration tool refuses a comment inside [MaesterTest(...)] - 'a rewrite would lose it' - and that threw before it printed its summary, which is the line TestAttributes.Tests.ps1 asserts on. Verified against main: 171/171 there, one red here, so it was mine and not pre-existing. The note now sits above the attribute, and the two files were run through build/migration/Convert-MtTestAttributes.ps1 so the property order matches the rest of the repo. The tool now reports Changed=0 Reordered=0, the same as main. --- tests/maester/defender/Test.MT.1269.ps1 | 2 +- tests/maester/defender/Test.MT.1270.ps1 | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/maester/defender/Test.MT.1269.ps1 b/tests/maester/defender/Test.MT.1269.ps1 index 8b7feab7ac..d8c1c5db9a 100644 --- a/tests/maester/defender/Test.MT.1269.ps1 +++ b/tests/maester/defender/Test.MT.1269.ps1 @@ -93,9 +93,9 @@ function Test-MtDefenderDeviceSecurityRecommendation { UserImpact = 'Medium', ImplementationCost = 'Medium', Mitre = 'None', - Lifecycle = 'Preview', Service = 'Graph', License = 'DEFENDER_XDR', + Lifecycle = 'Preview', InstanceSource = 'Get-MtDefenderDeviceSecurityRecommendationInstance', Author = 'earbona23' )] diff --git a/tests/maester/defender/Test.MT.1270.ps1 b/tests/maester/defender/Test.MT.1270.ps1 index 23f69135d3..3cf21d4108 100644 --- a/tests/maester/defender/Test.MT.1270.ps1 +++ b/tests/maester/defender/Test.MT.1270.ps1 @@ -34,6 +34,11 @@ .LINK https://maester.dev/docs/commands/Test-MtDefenderExploitableSoftwareVulnerability #> + # On Mitre: not T1190, which is about exploiting a public-facing application - this check + # never establishes that anything is reachable from outside, so it would misclassify a + # fleet of internal or client software. T1203 is what patching this software actually + # prevents on an endpoint. 'None' was wrong too: the attribute review reads the + # description as naming attacker behaviour, which it does. [MaesterTest( Id = 'MT.1270', Title = 'Devices should not run software with a publicly exploitable high or critical vulnerability.', @@ -44,15 +49,10 @@ Severity = 'Medium', UserImpact = 'Medium', ImplementationCost = 'Medium', - # Not T1190: that technique is about exploiting a public-facing application, and this - # check never establishes that anything is reachable from outside, so it would - # misclassify a fleet of internal or client software. T1203 is what patching this - # software actually prevents on an endpoint. `None` was wrong too: the attribute - # review reads the description as naming attacker behaviour, which it does. Mitre = 'T1203', - Lifecycle = 'Preview', Service = 'Graph', License = 'DEFENDER_XDR', + Lifecycle = 'Preview', Author = 'earbona23' )] [CmdletBinding()] From 3ee0387a0deabca8416036616b28c738c1153e3b Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:39:50 -0400 Subject: [PATCH 10/14] fix(defender): MT.1269 and MT.1270 probe advanced hunting before querying it On a tenant whose Defender for Endpoint tables are not served by advanced hunting, both checks ended in Error carrying the API's own text, which on such a tenant can be as little as ". Fix semantic errors in your query." That names neither the table nor the cause, so it reads as a defect in the check rather than as a tenant that cannot answer the question. No licence gate detects it. A tenant holding both Defender for Business and Defender for Endpoint Plan 2 keeps the Defender for Business experience until Support switches it, and advanced hunting belongs to Plan 2 only, so DEFENDER_XDR passes and a gate on Plan 2 would pass too. Both checks now probe DeviceInfo first and skip with a reason that says what is missing and names that licensing state as one cause. The probe query is a constant, which is what makes its failure attributable to the tenant rather than to anything a caller composed; an empty result counts as available, since a table that resolves and returns no row has answered, and the no-data skips keep their own reasons. MT.1087 on main takes the same path and is left for its own change. Measured by julien-ly on a lab tenant with Business Premium and an E5 trial, three runs over about eight hours. --- ...est-MtDefenderAdvancedHuntingAvailable.ps1 | 50 +++++++++++++++++++ tests/maester/defender/Test.MT.1269.md | 1 + tests/maester/defender/Test.MT.1269.ps1 | 9 ++++ tests/maester/defender/Test.MT.1270.md | 1 + tests/maester/defender/Test.MT.1270.ps1 | 8 +++ 5 files changed, 69 insertions(+) create mode 100644 powershell/internal/services/defender/Test-MtDefenderAdvancedHuntingAvailable.ps1 diff --git a/powershell/internal/services/defender/Test-MtDefenderAdvancedHuntingAvailable.ps1 b/powershell/internal/services/defender/Test-MtDefenderAdvancedHuntingAvailable.ps1 new file mode 100644 index 0000000000..9641a635c0 --- /dev/null +++ b/powershell/internal/services/defender/Test-MtDefenderAdvancedHuntingAvailable.ps1 @@ -0,0 +1,50 @@ +function Test-MtDefenderAdvancedHuntingAvailable { + <# + .SYNOPSIS + Returns whether the Defender for Endpoint device tables answer advanced hunting on this tenant. + + .DESCRIPTION + The Defender Vulnerability Management checks read DeviceTvm* tables through advanced hunting. On a + tenant where those tables are not served, the query comes back as an execution error and the check + ends in Error with the API's own text, which on some tenants is reduced to + ". Fix semantic errors in your query." and does not even name the table. That reads as a defect in + the check rather than as a tenant that cannot answer the question. + + A licence gate cannot tell the two apart. A tenant holding both Defender for Business (from Business + Premium) and Defender for Endpoint Plan 2 (for instance from an E5 trial) keeps the Defender for + Business experience until Support switches it, and advanced hunting belongs to Plan 2 only. Both + DEFENDER_XDR and a gate on Plan 2 pass on such a tenant while the tables stay silent. + + So this probes instead of inferring. The query is a constant and minimal one over DeviceInfo, the + table every Defender for Endpoint device reports into. It cannot fail because of anything a caller + composed, which is what makes its failure attributable to the tenant rather than to the query. + + An empty result is availability, not absence: a table that resolves and returns no row has answered. + The distinction matters, because a tenant with no onboarded device must still be skipped by the + caller's own no-data path, with its own reason. + + .OUTPUTS + [bool] - True when the Defender for Endpoint tables answer, false when they do not. + + .EXAMPLE + Test-MtDefenderAdvancedHuntingAvailable + + Returns $true on a tenant whose Defender for Endpoint tables are served by advanced hunting. + #> + [CmdletBinding()] + [OutputType([bool])] + param() + + try { + $null = Invoke-MtGraphSecurityQuery -Query 'DeviceInfo | project DeviceId | take 1' -Timespan 'P1D' + return $true + } catch { + # Deliberately broad. Invoke-MtGraphSecurityQuery surfaces the API's message, and that message is + # not reliable enough to match on: the same unavailability reaches us as + # "Failed to resolve table or column expression named ..." for some tables and as + # ". Fix semantic errors in your query." for others. Matching the text would make the probe fail + # open on the tenants it exists for. The query being a constant is what bounds this catch. + Write-Verbose "Defender for Endpoint tables did not answer advanced hunting: $($_.Exception.Message)" + return $false + } +} diff --git a/tests/maester/defender/Test.MT.1269.md b/tests/maester/defender/Test.MT.1269.md index df2518624e..97364015a2 100644 --- a/tests/maester/defender/Test.MT.1269.md +++ b/tests/maester/defender/Test.MT.1269.md @@ -14,6 +14,7 @@ Only configurations Defender reports as **applicable to at least one device** ar - **No Defender Vulnerability Management data.** When the hunting query returns no assessment, no device is onboarded to Defender for Endpoint or none has reported. The family is skipped with `NoInstances`. A tenant with no onboarded device has no configuration to be compliant with, and is never reported as having none non-compliant. - **Not licensed.** The check declares `DEFENDER_XDR`, so a tenant without a Defender XDR workload is skipped as not licensed, never failed. +- **Advanced hunting does not serve the Defender for Endpoint tables.** The check probes `DeviceInfo` before its own query and skips when that table does not answer. A tenant holding both Defender for Business (from Business Premium) and Defender for Endpoint Plan 2 (for instance from an E5 trial) keeps the [Defender for Business experience](https://learn.microsoft.com/defender-business/mdb-faq#can-i-have-a-mix-of-microsoft-endpoint-security-subscriptions) until Support switches it, and [advanced hunting belongs to Plan 2 only](https://learn.microsoft.com/defender-business/mdb-overview#how-does-defender-for-business-compare-to-microsoft-defender-for-endpoint). A licence gate cannot see this: `DEFENDER_XDR` passes, and so would a gate on Plan 2. Without the probe the check ends in `Error` carrying the API's own text, which on such a tenant can be as little as `". Fix semantic errors in your query."`. ## How to remediate diff --git a/tests/maester/defender/Test.MT.1269.ps1 b/tests/maester/defender/Test.MT.1269.ps1 index d8c1c5db9a..58adc7ddc5 100644 --- a/tests/maester/defender/Test.MT.1269.ps1 +++ b/tests/maester/defender/Test.MT.1269.ps1 @@ -16,6 +16,15 @@ [OutputType([pscustomobject])] param() + # Probed before the real query. Without this, a tenant whose Defender for Endpoint tables are not + # served by advanced hunting ends the whole family in Error carrying the API's own text, which can be + # as little as ". Fix semantic errors in your query." - a message that points at this check rather + # than at the tenant. See Test-MtDefenderAdvancedHuntingAvailable for why no licence gate detects it. + if (-not (Test-MtDefenderAdvancedHuntingAvailable)) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Defender for Endpoint tables are not available in advanced hunting on this tenant. A tenant holding both Defender for Business and Defender for Endpoint Plan 2 keeps the Defender for Business experience, which has no advanced hunting, until Support switches it.' + return + } + $configurations = Get-MtDefenderSecureConfigurationAssessment foreach ($configuration in $configurations) { diff --git a/tests/maester/defender/Test.MT.1270.md b/tests/maester/defender/Test.MT.1270.md index ea81cfce46..44fc07e82a 100644 --- a/tests/maester/defender/Test.MT.1270.md +++ b/tests/maester/defender/Test.MT.1270.md @@ -31,6 +31,7 @@ the intended reading, not a contradiction. - **Nothing assessed.** The check carries the number of distinct devices Defender has any vulnerability data for as a denominator. When that is zero, no device is onboarded to Defender for Endpoint or none has reported, and the result is skipped as not applicable. **Zero exposed devices out of zero assessed devices is not a pass.** - **Not licensed.** The check declares `DEFENDER_XDR`, so a tenant without a Defender XDR workload is skipped as not licensed, never failed. +- **Advanced hunting does not serve the Defender for Endpoint tables.** The check probes `DeviceInfo` before its own query and skips when that table does not answer. A tenant holding both Defender for Business (from Business Premium) and Defender for Endpoint Plan 2 (for instance from an E5 trial) keeps the [Defender for Business experience](https://learn.microsoft.com/defender-business/mdb-faq#can-i-have-a-mix-of-microsoft-endpoint-security-subscriptions) until Support switches it, and [advanced hunting belongs to Plan 2 only](https://learn.microsoft.com/defender-business/mdb-overview#how-does-defender-for-business-compare-to-microsoft-defender-for-endpoint). A licence gate cannot see this: `DEFENDER_XDR` passes, and so would a gate on Plan 2. Without the probe the check ends in `Error` carrying the API's own text, which on such a tenant can be as little as `". Fix semantic errors in your query."`. ## How to remediate diff --git a/tests/maester/defender/Test.MT.1270.ps1 b/tests/maester/defender/Test.MT.1270.ps1 index 3cf21d4108..fbbf71a30a 100644 --- a/tests/maester/defender/Test.MT.1270.ps1 +++ b/tests/maester/defender/Test.MT.1270.ps1 @@ -59,6 +59,14 @@ [OutputType([bool])] param() + # Same probe as MT.1269: a tenant whose Defender for Endpoint tables are not served by advanced + # hunting would otherwise end in Error with the API's own text rather than with a reason an + # assessor can act on. + if (-not (Test-MtDefenderAdvancedHuntingAvailable)) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Defender for Endpoint tables are not available in advanced hunting on this tenant. A tenant holding both Defender for Business and Defender for Endpoint Plan 2 keeps the Defender for Business experience, which has no advanced hunting, until Support switches it.' + return $null + } + $summary = Get-MtDefenderExploitableVulnerability if ($null -eq $summary) { # Defender returned no result set at all. Report a skip rather than a clean fleet. From b4042410445e5e441f70eba934bffe15ae270202 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:49:44 -0400 Subject: [PATCH 11/14] test(defender): cover the advanced hunting probe, and MT.1270 states why it skips Two things the probe commit left undone. The tests mocked the data helpers rather than the query, so nothing exercised the probe and every test that reaches a check through it was running the real one: six of them went from passing to skipping and the file was red. The default is now that the tables answer, with the probe's own behaviour covered explicitly: available on a row, available on an empty result, unavailable on either of the two messages Defender sends for the same condition, and the Verbose line that keeps the failure from being silent. Two more assert that each check skips with a reason of its own and never reaches its query. MT.1270's own two skips still said NotApplicable, which is what #2694 is changing in MT.1268 for being untrue next to the detail it sits by. They now say what is missing: no result set at all, or no device with any vulnerability data. Leaving them would have meant shipping an assertion that fixes wording this author argued against on the same day. The no-data skip and the unavailable-tables skip are both Custom now, so a test asserts the reasons stay distinct. They are different situations: a tenant with no onboarded device has answered the question, and a tenant whose tables do not answer has not. 26 of 26 pass on Pester 5.7.1, the version the CI pins. --- ...tDefenderVulnerabilityManagement.Tests.ps1 | 90 ++++++++++++++++++- tests/maester/defender/Test.MT.1270.md | 2 +- tests/maester/defender/Test.MT.1270.ps1 | 4 +- 3 files changed, 89 insertions(+), 7 deletions(-) diff --git a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 index 1afe80c08c..f534ee065e 100644 --- a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 @@ -7,7 +7,8 @@ Get-MtDefenderDeviceSecurityRecommendationInstance, Test-MtDefenderExploitableSoftwareVulnerability, Get-MtDefenderSecureConfigurationAssessment, - Get-MtDefenderExploitableVulnerability + Get-MtDefenderExploitableVulnerability, + Test-MtDefenderAdvancedHuntingAvailable function Get-TestConfiguration { param( @@ -53,14 +54,19 @@ BeforeEach { $script:TestResult = $null $script:SkippedBecause = $null + $script:SkippedCustomReason = $null $script:Severity = $null Mock -ModuleName Maester Get-MtLicenseInformation { return $true } + # The default is "the tables answer", so the tests below exercise what they are about. + # The probe's own behaviour, and the skip it produces, are covered explicitly further down. + Mock -ModuleName Maester Test-MtDefenderAdvancedHuntingAvailable { return $true } Mock -ModuleName Maester Add-MtTestResultDetail { - param($Result, $SkippedBecause, $Severity) + param($Result, $SkippedBecause, $SkippedCustomReason, $Severity) $script:TestResult = $Result $script:SkippedBecause = $SkippedBecause + $script:SkippedCustomReason = $SkippedCustomReason $script:Severity = $Severity } } @@ -196,14 +202,16 @@ } $null -eq (Test-MtDefenderExploitableSoftwareVulnerability) | Should -BeTrue - $script:SkippedBecause | Should -Be 'NotApplicable' + $script:SkippedBecause | Should -Be 'Custom' + $script:SkippedCustomReason | Should -Match 'no fleet to judge' } It 'skips when Defender returns no result set at all' { Mock -ModuleName Maester Get-MtDefenderExploitableVulnerability { return $null } $null -eq (Test-MtDefenderExploitableSoftwareVulnerability) | Should -BeTrue - $script:SkippedBecause | Should -Be 'NotApplicable' + $script:SkippedBecause | Should -Be 'Custom' + $script:SkippedCustomReason | Should -Match 'no result set' } } @@ -268,4 +276,78 @@ $null -eq (Get-MtDefenderExploitableVulnerability) | Should -BeTrue } } + + Context 'Test-MtDefenderAdvancedHuntingAvailable' { + It 'reports available when the probe query answers' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @([pscustomobject]@{ DeviceId = 'd1' }) } + + Test-MtDefenderAdvancedHuntingAvailable | Should -BeTrue + } + + It 'reports available when the table answers with no row' { + # A table that resolves and returns nothing has answered. Reading an empty result as + # unavailable would skip every tenant with no onboarded device for the wrong reason, and + # those tenants have their own skip with its own wording. + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @() } + + Test-MtDefenderAdvancedHuntingAvailable | Should -BeTrue + } + + It 'reports unavailable when the probe query throws' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw ". Fix semantic errors in your query." } + + Test-MtDefenderAdvancedHuntingAvailable | Should -BeFalse + } + + It 'reports unavailable on the message that names the table too' { + # The same unavailability reaches the caller as either message depending on the table, which + # is why neither is matched on. + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw "Failed to resolve table or column expression named 'DeviceInfo'" } + + Test-MtDefenderAdvancedHuntingAvailable | Should -BeFalse + } + + It 'does not swallow the failure silently' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw 'boom' } + + $verbose = Test-MtDefenderAdvancedHuntingAvailable -Verbose 4>&1 | Where-Object { $_ -is [System.Management.Automation.VerboseRecord] } + ($verbose -join ' ') | Should -Match 'did not answer advanced hunting' + } + } + + Context 'The checks skip rather than error when advanced hunting does not serve the tables' { + It 'MT.1269 skips with a reason of its own and never runs its query' { + Mock -ModuleName Maester Test-MtDefenderAdvancedHuntingAvailable { return $false } + Mock -ModuleName Maester Get-MtDefenderSecureConfigurationAssessment { throw 'the instance source must not reach this' } + + $instances = @(Get-MtDefenderDeviceSecurityRecommendationInstance) + + $instances.Count | Should -Be 0 + $script:SkippedBecause | Should -Be 'Custom' + Should -Invoke -ModuleName Maester Get-MtDefenderSecureConfigurationAssessment -Times 0 -Exactly + } + + It 'MT.1270 skips with a reason of its own and never runs its query' { + Mock -ModuleName Maester Test-MtDefenderAdvancedHuntingAvailable { return $false } + Mock -ModuleName Maester Get-MtDefenderExploitableVulnerability { throw 'the check must not reach this' } + + $null -eq (Test-MtDefenderExploitableSoftwareVulnerability) | Should -BeTrue + $script:SkippedBecause | Should -Be 'Custom' + Should -Invoke -ModuleName Maester Get-MtDefenderExploitableVulnerability -Times 0 -Exactly + } + + It 'keeps the no-data skip distinct from the unavailable-tables skip' { + # Two different situations that must not share a reason: a tenant with no onboarded device + # has answered the question, and a tenant whose tables do not answer has not. + Mock -ModuleName Maester Test-MtDefenderAdvancedHuntingAvailable { return $true } + Mock -ModuleName Maester Get-MtDefenderExploitableVulnerability { + [pscustomobject]@{ AssessedDeviceCount = 0; ExposedDeviceCount = 0; CveCount = 0; TopCveList = @(); TopSoftwareList = @() } + } + + $null -eq (Test-MtDefenderExploitableSoftwareVulnerability) | Should -BeTrue + $script:SkippedBecause | Should -Be 'Custom' + $script:SkippedCustomReason | Should -Match 'no fleet to judge' + $script:SkippedCustomReason | Should -Not -Match 'advanced hunting' + } + } } diff --git a/tests/maester/defender/Test.MT.1270.md b/tests/maester/defender/Test.MT.1270.md index 44fc07e82a..f17297e591 100644 --- a/tests/maester/defender/Test.MT.1270.md +++ b/tests/maester/defender/Test.MT.1270.md @@ -29,7 +29,7 @@ the intended reading, not a contradiction. ## When this is skipped -- **Nothing assessed.** The check carries the number of distinct devices Defender has any vulnerability data for as a denominator. When that is zero, no device is onboarded to Defender for Endpoint or none has reported, and the result is skipped as not applicable. **Zero exposed devices out of zero assessed devices is not a pass.** +- **Nothing assessed.** The check carries the number of distinct devices Defender has any vulnerability data for as a denominator. When that is zero, no device is onboarded to Defender for Endpoint or none has reported, and the result is skipped with that stated as the reason. **Zero exposed devices out of zero assessed devices is not a pass.** - **Not licensed.** The check declares `DEFENDER_XDR`, so a tenant without a Defender XDR workload is skipped as not licensed, never failed. - **Advanced hunting does not serve the Defender for Endpoint tables.** The check probes `DeviceInfo` before its own query and skips when that table does not answer. A tenant holding both Defender for Business (from Business Premium) and Defender for Endpoint Plan 2 (for instance from an E5 trial) keeps the [Defender for Business experience](https://learn.microsoft.com/defender-business/mdb-faq#can-i-have-a-mix-of-microsoft-endpoint-security-subscriptions) until Support switches it, and [advanced hunting belongs to Plan 2 only](https://learn.microsoft.com/defender-business/mdb-overview#how-does-defender-for-business-compare-to-microsoft-defender-for-endpoint). A licence gate cannot see this: `DEFENDER_XDR` passes, and so would a gate on Plan 2. Without the probe the check ends in `Error` carrying the API's own text, which on such a tenant can be as little as `". Fix semantic errors in your query."`. diff --git a/tests/maester/defender/Test.MT.1270.ps1 b/tests/maester/defender/Test.MT.1270.ps1 index fbbf71a30a..1fb11c6c81 100644 --- a/tests/maester/defender/Test.MT.1270.ps1 +++ b/tests/maester/defender/Test.MT.1270.ps1 @@ -70,14 +70,14 @@ $summary = Get-MtDefenderExploitableVulnerability if ($null -eq $summary) { # Defender returned no result set at all. Report a skip rather than a clean fleet. - Add-MtTestResultDetail -SkippedBecause NotApplicable + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Defender Vulnerability Management returned no result set for this tenant, so there is no fleet to judge.' return $null } if ($summary.AssessedDeviceCount -le 0) { # No device has any vulnerability data, so there is no fleet to judge. Zero exposed out of zero # assessed is not a pass. - Add-MtTestResultDetail -SkippedBecause NotApplicable + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'No device has any Defender Vulnerability Management data, so there is no fleet to judge. Zero exposed devices out of zero assessed is not a pass.' return $null } From 92c1e3987e35a923556017e05c94af7e4f4524fc Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:53:32 -0400 Subject: [PATCH 12/14] test(defender): the probe's own tests move to their own file Test-MtDefenderAdvancedHuntingAvailable is a helper of its own, and its tests sat inside the file that covers MT.1269 and MT.1270. Moving them out keeps this file about the two checks, and lets the follow-up that adds the probe to MT.1087 carry the same helper and the same tests without either pull request conflicting with the other: both files are byte for byte identical on the two branches. The cases that stay here are the ones that are about the checks: each skips with a reason of its own and reaches no query, and the no-data skip keeps a reason distinct from the unavailable-tables one. One case is new in the move: the probe asks for exactly one query, and for that query. It runs ahead of every check that depends on it, so a probe that grew a second call or started pulling rows would be a cost on every tenant, including the ones where nothing is wrong. 21 of 21 here and 6 of 6 there, on Pester 5.7.1. --- ...DefenderAdvancedHuntingAvailable.Tests.ps1 | 59 +++++++++++++++++++ ...tDefenderVulnerabilityManagement.Tests.ps1 | 38 ------------ 2 files changed, 59 insertions(+), 38 deletions(-) create mode 100644 powershell/tests/functions/Test-MtDefenderAdvancedHuntingAvailable.Tests.ps1 diff --git a/powershell/tests/functions/Test-MtDefenderAdvancedHuntingAvailable.Tests.ps1 b/powershell/tests/functions/Test-MtDefenderAdvancedHuntingAvailable.Tests.ps1 new file mode 100644 index 0000000000..ed4387f558 --- /dev/null +++ b/powershell/tests/functions/Test-MtDefenderAdvancedHuntingAvailable.Tests.ps1 @@ -0,0 +1,59 @@ +Describe 'Test-MtDefenderAdvancedHuntingAvailable' { + BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + # An internal helper, so it is not exported. + Use-MtModuleFunction -Name Test-MtDefenderAdvancedHuntingAvailable + } + + It 'reports available when the probe query answers' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @([pscustomobject]@{ DeviceId = 'd1' }) } + + Test-MtDefenderAdvancedHuntingAvailable | Should -BeTrue + } + + It 'reports available when the table answers with no row' { + # A table that resolves and returns nothing has answered. Reading an empty result as + # unavailable would skip every tenant with no onboarded device for the wrong reason, and those + # tenants have their own skip with its own wording. + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @() } + + Test-MtDefenderAdvancedHuntingAvailable | Should -BeTrue + } + + It 'reports unavailable when the probe query throws' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw '. Fix semantic errors in your query.' } + + Test-MtDefenderAdvancedHuntingAvailable | Should -BeFalse + } + + It 'reports unavailable on the message that names the table too' { + # The same unavailability reaches the caller as either message depending on the table, which is + # why the catch does not match on the text. + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw "Failed to resolve table or column expression named 'DeviceInfo'" } + + Test-MtDefenderAdvancedHuntingAvailable | Should -BeFalse + } + + It 'asks only for what it needs, once' { + # The probe runs before every check that depends on it, so a probe that pulled rows would be a + # per-run cost on every tenant, including the ones where nothing is wrong. + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @() } + + $null = Test-MtDefenderAdvancedHuntingAvailable + + Should -Invoke -ModuleName Maester Invoke-MtGraphSecurityQuery -Times 1 -Exactly + Should -Invoke -ModuleName Maester Invoke-MtGraphSecurityQuery -ParameterFilter { + $Query -eq 'DeviceInfo | project DeviceId | take 1' + } -Times 1 -Exactly + } + + It 'does not swallow the failure silently' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw 'boom' } + + $verbose = Test-MtDefenderAdvancedHuntingAvailable -Verbose 4>&1 | + Where-Object { $_ -is [System.Management.Automation.VerboseRecord] } + + ($verbose -join ' ') | Should -Match 'did not answer advanced hunting' + } +} diff --git a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 index f534ee065e..59ffe228fd 100644 --- a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 @@ -277,44 +277,6 @@ } } - Context 'Test-MtDefenderAdvancedHuntingAvailable' { - It 'reports available when the probe query answers' { - Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @([pscustomobject]@{ DeviceId = 'd1' }) } - - Test-MtDefenderAdvancedHuntingAvailable | Should -BeTrue - } - - It 'reports available when the table answers with no row' { - # A table that resolves and returns nothing has answered. Reading an empty result as - # unavailable would skip every tenant with no onboarded device for the wrong reason, and - # those tenants have their own skip with its own wording. - Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @() } - - Test-MtDefenderAdvancedHuntingAvailable | Should -BeTrue - } - - It 'reports unavailable when the probe query throws' { - Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw ". Fix semantic errors in your query." } - - Test-MtDefenderAdvancedHuntingAvailable | Should -BeFalse - } - - It 'reports unavailable on the message that names the table too' { - # The same unavailability reaches the caller as either message depending on the table, which - # is why neither is matched on. - Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw "Failed to resolve table or column expression named 'DeviceInfo'" } - - Test-MtDefenderAdvancedHuntingAvailable | Should -BeFalse - } - - It 'does not swallow the failure silently' { - Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw 'boom' } - - $verbose = Test-MtDefenderAdvancedHuntingAvailable -Verbose 4>&1 | Where-Object { $_ -is [System.Management.Automation.VerboseRecord] } - ($verbose -join ' ') | Should -Match 'did not answer advanced hunting' - } - } - Context 'The checks skip rather than error when advanced hunting does not serve the tables' { It 'MT.1269 skips with a reason of its own and never runs its query' { Mock -ModuleName Maester Test-MtDefenderAdvancedHuntingAvailable { return $false } From aef280ef242e54a3a03fcd4a9dfd3084efe97560 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:29:53 -0400 Subject: [PATCH 13/14] test(defender): a query that cannot run must not read as a clean tenant Both helpers document that they catch nothing, because letting Invoke-MtGraphSecurityQuery's failure surface is what stops a broken query from being reported as a tenant with no non-compliant configuration and no exposed device. That contract was prose with nothing holding it: a later try/catch returning an empty list would pass every tenant and no test would notice. Four cases now hold it. Two on the helpers directly, and two on the checks after the probe has answered, which is the distinction the probe cannot make: the tables are served and the real query still fails. The MT.1269 one matters most, since emitting no instance there skips the family with NoInstances, a result that says the tenant has no assessed configuration. It has not said that; the query never ran. 25 of 25 on Pester 5.7.1. --- ...tDefenderVulnerabilityManagement.Tests.ps1 | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 index 59ffe228fd..1f4a5cf84e 100644 --- a/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 @@ -312,4 +312,41 @@ $script:SkippedCustomReason | Should -Not -Match 'advanced hunting' } } + + Context 'A query that cannot run must not read as a clean tenant' { + # Both helpers document that they catch nothing: Invoke-MtGraphSecurityQuery throws on a query + # execution error, and letting it surface is what stops a broken query from being reported as a + # tenant with no non-compliant configuration and no exposed device. That contract was prose with + # nothing holding it, so a later try/catch returning an empty list would pass every tenant and + # no test would notice. These are that holder. + + It 'Get-MtDefenderSecureConfigurationAssessment lets the failure surface' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw 'Query execution has failed.' } + + { Get-MtDefenderSecureConfigurationAssessment } | Should -Throw -ExpectedMessage '*Query execution has failed*' + } + + It 'Get-MtDefenderExploitableVulnerability lets the failure surface' { + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw 'Query execution has failed.' } + + { Get-MtDefenderExploitableVulnerability } | Should -Throw -ExpectedMessage '*Query execution has failed*' + } + + It 'MT.1269 errors rather than emitting nothing when the query fails after the probe answered' { + # The distinction the probe cannot make: the tables answer, and the real query still fails. + # Emitting no instance here would skip the family with NoInstances, which says the tenant has + # no assessed configuration. It has not said that; the query never ran. + Mock -ModuleName Maester Test-MtDefenderAdvancedHuntingAvailable { return $true } + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw 'Query execution has failed.' } + + { Get-MtDefenderDeviceSecurityRecommendationInstance } | Should -Throw + } + + It 'MT.1270 errors rather than passing when the query fails after the probe answered' { + Mock -ModuleName Maester Test-MtDefenderAdvancedHuntingAvailable { return $true } + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw 'Query execution has failed.' } + + { Test-MtDefenderExploitableSoftwareVulnerability } | Should -Throw + } + } } From c4f34b8b2ae035d8a27f3971c1560a8b3f2f8198 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:11:46 -0400 Subject: [PATCH 14/14] perf(defender): the advanced hunting probe is read once per run Three checks depend on the probe and Invoke-MtGraphSecurityQuery does not cache, so every run asked the same question three times. Advanced hunting is rate limited and the answer is a property of the tenant, not of the caller, so it is now kept in $__MtSession.DefenderHuntingTables and Invoke-Maester clears it between runs, the same shape AIAgentInfo uses. The unavailable answer is cached too, which is the case that matters: without it the tenants this guard exists for pay a failing query per check. GraphCacheUsage.Tests.ps1 forbids a session cache write in a check, not in a helper, and this is a helper; the probe still never bypasses the Graph cache. Three cases added: the query is asked once across three calls, a false answer is cached as well, and a cleared run cache asks again so a second run on a tenant whose licensing changed is not answered from the first. Each case resets the cache first, or it would read the previous one's answer and pass no matter what. 8 of 8 on the probe, 2349 of 2349 with the Defender suite and GraphCacheUsage. --- powershell/Maester.psm1 | 1 + ...est-MtDefenderAdvancedHuntingAvailable.ps1 | 11 ++++++ .../internal/session/Clear-ModuleVariable.ps1 | 1 + ...DefenderAdvancedHuntingAvailable.Tests.ps1 | 38 +++++++++++++++++-- 4 files changed, 48 insertions(+), 3 deletions(-) diff --git a/powershell/Maester.psm1 b/powershell/Maester.psm1 index ff65045908..76fb4655ca 100644 --- a/powershell/Maester.psm1 +++ b/powershell/Maester.psm1 @@ -26,6 +26,7 @@ $__MtSession = @{ ExoCache = @{} OrcaCache = @{} AIAgentInfo = $null # Get-MtAIAgentInfo cache: @{ Agents; Error }, Error is why no agent data is available + DefenderHuntingTables = $null # Test-MtDefenderAdvancedHuntingAvailable cache: $true when the Defender for Endpoint tables answer AzureDevOpsConnectionCache = $null DataverseApiBase = $null # Resolved Dataverse OData API base URL (e.g. https://org123.api.crm.dynamics.com/api/data/v9.2) DataverseResourceUrl = $null # Dataverse resource URL for token acquisition (e.g. https://org123.crm.dynamics.com) diff --git a/powershell/internal/services/defender/Test-MtDefenderAdvancedHuntingAvailable.ps1 b/powershell/internal/services/defender/Test-MtDefenderAdvancedHuntingAvailable.ps1 index 9641a635c0..d3369cbfa7 100644 --- a/powershell/internal/services/defender/Test-MtDefenderAdvancedHuntingAvailable.ps1 +++ b/powershell/internal/services/defender/Test-MtDefenderAdvancedHuntingAvailable.ps1 @@ -23,6 +23,11 @@ The distinction matters, because a tenant with no onboarded device must still be skipped by the caller's own no-data path, with its own reason. + The answer is a property of the tenant, not of the caller, so it is read once per run and kept in + $__MtSession.DefenderHuntingTables. Three checks depend on it and advanced hunting is rate limited; + asking the same question three times a run is a cost paid by every tenant, including the ones where + nothing is wrong. Invoke-Maester clears it between runs. + .OUTPUTS [bool] - True when the Defender for Endpoint tables answer, false when they do not. @@ -35,8 +40,13 @@ [OutputType([bool])] param() + if ($null -ne $__MtSession.DefenderHuntingTables) { + return [bool]$__MtSession.DefenderHuntingTables + } + try { $null = Invoke-MtGraphSecurityQuery -Query 'DeviceInfo | project DeviceId | take 1' -Timespan 'P1D' + $__MtSession.DefenderHuntingTables = $true return $true } catch { # Deliberately broad. Invoke-MtGraphSecurityQuery surfaces the API's message, and that message is @@ -45,6 +55,7 @@ # ". Fix semantic errors in your query." for others. Matching the text would make the probe fail # open on the tenants it exists for. The query being a constant is what bounds this catch. Write-Verbose "Defender for Endpoint tables did not answer advanced hunting: $($_.Exception.Message)" + $__MtSession.DefenderHuntingTables = $false return $false } } diff --git a/powershell/internal/session/Clear-ModuleVariable.ps1 b/powershell/internal/session/Clear-ModuleVariable.ps1 index 2c4eb15b76..98fac07eb7 100644 --- a/powershell/internal/session/Clear-ModuleVariable.ps1 +++ b/powershell/internal/session/Clear-ModuleVariable.ps1 @@ -25,6 +25,7 @@ Clear-MtExoCache Clear-MtADCache $__MtSession.AIAgentInfo = $null + $__MtSession.DefenderHuntingTables = $null $__MtSession.IncludeAffectedObjects = $false $__MtSession.AffectedObjectFacts = $null $__MtSession.AzureDevOpsConnectionCache = $null diff --git a/powershell/tests/functions/Test-MtDefenderAdvancedHuntingAvailable.Tests.ps1 b/powershell/tests/functions/Test-MtDefenderAdvancedHuntingAvailable.Tests.ps1 index ed4387f558..f1789972be 100644 --- a/powershell/tests/functions/Test-MtDefenderAdvancedHuntingAvailable.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDefenderAdvancedHuntingAvailable.Tests.ps1 @@ -6,6 +6,12 @@ Use-MtModuleFunction -Name Test-MtDefenderAdvancedHuntingAvailable } + BeforeEach { + # The answer is cached for the run. Without this each case would read the previous one's result + # and the probe would appear to work no matter what it was given. + InModuleScope Maester { $__MtSession.DefenderHuntingTables = $null } + } + It 'reports available when the probe query answers' { Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @([pscustomobject]@{ DeviceId = 'd1' }) } @@ -35,11 +41,14 @@ Test-MtDefenderAdvancedHuntingAvailable | Should -BeFalse } - It 'asks only for what it needs, once' { - # The probe runs before every check that depends on it, so a probe that pulled rows would be a - # per-run cost on every tenant, including the ones where nothing is wrong. + It 'asks only for what it needs, and only once per run' { + # Three checks depend on this and advanced hunting is rate limited, so the question is asked + # once and kept for the run. A probe that pulled rows, or asked again per check, would be a cost + # on every tenant, including the ones where nothing is wrong. Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @() } + $null = Test-MtDefenderAdvancedHuntingAvailable + $null = Test-MtDefenderAdvancedHuntingAvailable $null = Test-MtDefenderAdvancedHuntingAvailable Should -Invoke -ModuleName Maester Invoke-MtGraphSecurityQuery -Times 1 -Exactly @@ -48,6 +57,29 @@ } -Times 1 -Exactly } + It 'caches the unavailable answer too, rather than retrying per check' { + # The expensive case is the one that fails: without this the tenant pays a failing query for + # every check that depends on the probe. + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw 'Query execution has failed.' } + + Test-MtDefenderAdvancedHuntingAvailable | Should -BeFalse + Test-MtDefenderAdvancedHuntingAvailable | Should -BeFalse + + Should -Invoke -ModuleName Maester Invoke-MtGraphSecurityQuery -Times 1 -Exactly + } + + It 'asks again once the run cache is cleared' { + # Invoke-Maester clears the per-run cache, so a second run on a tenant whose licensing changed + # must not be answered from the first. + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { @() } + + $null = Test-MtDefenderAdvancedHuntingAvailable + InModuleScope Maester { $__MtSession.DefenderHuntingTables = $null } + $null = Test-MtDefenderAdvancedHuntingAvailable + + Should -Invoke -ModuleName Maester Invoke-MtGraphSecurityQuery -Times 2 -Exactly + } + It 'does not swallow the failure silently' { Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw 'boom' }