From 11c45c2401841717e4388f06de564d7eac31577c Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:54:12 -0400 Subject: [PATCH 1/3] fix(xspm): MT.1087 probes advanced hunting before querying it On a tenant whose Defender for Endpoint tables are not served by advanced hunting, this 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." 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. The check's own guard does not help. It reads DeviceNetworkEvents and DeviceTvmSoftwareVulnerabilities, and the assessed-device fallback that keeps an empty result from passing reads DeviceTvmSoftwareInventory, so the first query throws and that guard is never reached. No licence gate detects it either. 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 a gate on either passes while the tables stay silent. The check now probes DeviceInfo first and skips with a reason that says what is missing and names that licensing state as one cause. MT.1084 already guards this way for DeviceInfo and IdentityLogonEvents, so the shape is the one already in the tree; what is new is that the probe is a shared helper rather than a fourth copy of the pattern. An empty result counts as available: a table that resolves and returns no row has answered, and the no-data skip keeps its own reason. The helper and its tests are byte for byte identical to the ones in #2695, so the two can land in either order without conflicting. Measured by julien-ly on #2695, on a lab tenant with Business Premium and an E5 trial, three runs over about eight hours. --- ...est-MtDefenderAdvancedHuntingAvailable.ps1 | 50 ++++++++++++++++ ...DefenderAdvancedHuntingAvailable.Tests.ps1 | 59 +++++++++++++++++++ ...lyExploitableHighExposureDevices.Tests.ps1 | 23 +++++++- tests/maester/xspm/Test.MT.1087.md | 4 ++ tests/maester/xspm/Test.MT.1087.ps1 | 11 ++++ 5 files changed, 145 insertions(+), 2 deletions(-) create mode 100644 powershell/internal/services/defender/Test-MtDefenderAdvancedHuntingAvailable.ps1 create mode 100644 powershell/tests/functions/Test-MtDefenderAdvancedHuntingAvailable.Tests.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/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-MtXspmPublicRemotelyExploitableHighExposureDevices.Tests.ps1 b/powershell/tests/functions/Test-MtXspmPublicRemotelyExploitableHighExposureDevices.Tests.ps1 index 9642f4767f..11b4d340fe 100644 --- a/powershell/tests/functions/Test-MtXspmPublicRemotelyExploitableHighExposureDevices.Tests.ps1 +++ b/powershell/tests/functions/Test-MtXspmPublicRemotelyExploitableHighExposureDevices.Tests.ps1 @@ -3,19 +3,25 @@ Import-Module $PSScriptRoot/../../Maester.psd1 -Force . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" # The check is a native test, so the function is not exported. - Use-MtModuleFunction -Name Test-MtXspmPublicRemotelyExploitableHighExposureDevices + Use-MtModuleFunction -Name Test-MtXspmPublicRemotelyExploitableHighExposureDevices, + Test-MtDefenderAdvancedHuntingAvailable } BeforeEach { $script:TestResult = $null $script:SkippedBecause = $null + $script:SkippedCustomReason = $null Mock -ModuleName Maester Get-MtLicenseInformation { return $true } + # The default is "the tables answer", so the cases below exercise what they are about and the + # call counts stay about this check's own queries. The probe has its own case at the end. + Mock -ModuleName Maester Test-MtDefenderAdvancedHuntingAvailable { return $true } Mock -ModuleName Maester Add-MtTestResultDetail { - param($Result, $SkippedBecause) + param($Result, $SkippedBecause, $SkippedCustomReason) $script:TestResult = $Result $script:SkippedBecause = $SkippedBecause + $script:SkippedCustomReason = $SkippedCustomReason } } @@ -114,4 +120,17 @@ $null = Test-MtXspmPublicRemotelyExploitableHighExposureDevices Should -Invoke -ModuleName Maester Invoke-MtGraphSecurityQuery -Times 1 -Exactly } + + It 'skips with a reason of its own, and runs no query, when the tables do not answer' { + # Without this the first query throws, the check ends in Error with the API's own text, and the + # assessed-device guard above is never reached. Two different situations that must not share a + # reason: a tenant with no onboarded device has answered the question, this one has not. + Mock -ModuleName Maester Test-MtDefenderAdvancedHuntingAvailable { return $false } + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw 'the check must not reach this' } + + $null -eq (Test-MtXspmPublicRemotelyExploitableHighExposureDevices) | Should -BeTrue + $script:SkippedBecause | Should -Be 'Custom' + $script:SkippedCustomReason | Should -Match 'not available in advanced hunting' + Should -Invoke -ModuleName Maester Invoke-MtGraphSecurityQuery -Times 0 -Exactly + } } diff --git a/tests/maester/xspm/Test.MT.1087.md b/tests/maester/xspm/Test.MT.1087.md index 070b322c87..2b994c312a 100644 --- a/tests/maester/xspm/Test.MT.1087.md +++ b/tests/maester/xspm/Test.MT.1087.md @@ -14,6 +14,10 @@ Devices that return from these results are possible high-risk devices that could ### How to fix Review the devices in the list and either patch the severities, or make sure to implement mitigative controls to reduce exposure. If you want to have more details on the exposed devices and their related CVE's, you can [run the following query manually](https://github.com/HybridBrothers/Hunting-Queries-Detection-Rules/blob/main/Exposure%20Management/HuntPublicRemotelyExploitableDevicesWithHighEPSS.md) in Advanced Hunting. +### When this is skipped +- **Advanced hunting does not serve the Defender for Endpoint tables.** This check reads `DeviceNetworkEvents` and `DeviceTvmSoftwareVulnerabilities`, and its assessed-device fallback reads `DeviceTvmSoftwareInventory`. It probes `DeviceInfo` before either 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: the tenant holds the entitlement and not the experience. +- **Nothing assessed.** When no device has any software inventory in Defender Vulnerability Management, there is no fleet to judge. Zero exposed devices out of zero assessed devices is not a pass. + %TestResult% diff --git a/tests/maester/xspm/Test.MT.1087.ps1 b/tests/maester/xspm/Test.MT.1087.ps1 index 82c3ea8286..ad708846eb 100644 --- a/tests/maester/xspm/Test.MT.1087.ps1 +++ b/tests/maester/xspm/Test.MT.1087.ps1 @@ -42,6 +42,17 @@ [OutputType([bool])] param() + # Probed before either query. This check reads DeviceNetworkEvents and DeviceTvmSoftwareVulnerabilities, + # and its no-data fallback reads DeviceTvmSoftwareInventory, so on a tenant whose Defender for Endpoint + # tables are not served by advanced hunting both throw and 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." The + # existing assessed-device guard below never runs, because the throw happens first. + # MT.1084 already guards the same way for DeviceInfo and IdentityLogonEvents. + 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 + } + Write-Verbose "Get raw data from Exposure Management..." $Query = @" // Flag remotely exploitable, no user interaction, CVE's with a EPSS score above a certain threshold (likelihood of exploitation) From bfaf9f7f6570293f452c1f6666be367851aecad6 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:29:51 -0400 Subject: [PATCH 2/3] test(xspm): a query that cannot run must not read as a clean fleet MT.1087 reads an empty result as "no device matched", and its assessed-device count is what decides between a pass and a skip. Neither path had a case holding the behaviour when the query throws instead, so a later try/catch returning an empty result would report a clean fleet on a tenant whose query never ran, and nothing would fail. Two cases now hold it, both after the probe has answered, which is the distinction the probe cannot make: the tables are served and the real query still fails. 9 of 9 here and 6 of 6 for the probe, on Pester 5.7.1. --- ...lyExploitableHighExposureDevices.Tests.ps1 | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/powershell/tests/functions/Test-MtXspmPublicRemotelyExploitableHighExposureDevices.Tests.ps1 b/powershell/tests/functions/Test-MtXspmPublicRemotelyExploitableHighExposureDevices.Tests.ps1 index 11b4d340fe..77ca323553 100644 --- a/powershell/tests/functions/Test-MtXspmPublicRemotelyExploitableHighExposureDevices.Tests.ps1 +++ b/powershell/tests/functions/Test-MtXspmPublicRemotelyExploitableHighExposureDevices.Tests.ps1 @@ -133,4 +133,26 @@ $script:SkippedCustomReason | Should -Match 'not available in advanced hunting' Should -Invoke -ModuleName Maester Invoke-MtGraphSecurityQuery -Times 0 -Exactly } + + It 'errors rather than passing when the main query fails after the probe answered' { + # The distinction the probe cannot make: the tables answer, and the real query still fails. + # This check reads an empty result as "no device matched", so swallowing a failure here would + # report a clean fleet on a tenant whose query never ran. + Mock -ModuleName Maester Test-MtDefenderAdvancedHuntingAvailable { return $true } + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { throw 'Query execution has failed.' } + + { Test-MtXspmPublicRemotelyExploitableHighExposureDevices } | Should -Throw + } + + It 'errors rather than skipping when the denominator query fails' { + # The main query came back empty and the assessed-device count is what decides between a pass + # and a skip. If that query fails, neither answer has been earned. + Mock -ModuleName Maester Test-MtDefenderAdvancedHuntingAvailable { return $true } + Mock -ModuleName Maester Invoke-MtGraphSecurityQuery { + if ($Query -match 'summarize AssessedDeviceCount') { throw 'Query execution has failed.' } + return @() + } + + { Test-MtXspmPublicRemotelyExploitableHighExposureDevices } | Should -Throw + } } From 696ac79108e0bd02a627d2808398ad096668b18d 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 3/3] perf(defender): the advanced hunting probe is read once per run Same change as on #2695, byte for byte, so the two can still land in either order. Invoke-MtGraphSecurityQuery does not cache and three checks depend on the probe, so every run asked the same question three times. Advanced hunting is rate limited and the answer is a property of the tenant, so it is kept in $__MtSession.DefenderHuntingTables and Invoke-Maester clears it between runs, the same shape AIAgentInfo uses. The unavailable answer is cached too: without it the tenants this guard exists for pay a failing query per check. 2327 of 2327 with the MT.1087 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' }