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 new file mode 100644 index 0000000000..d3369cbfa7 --- /dev/null +++ b/powershell/internal/services/defender/Test-MtDefenderAdvancedHuntingAvailable.ps1 @@ -0,0 +1,61 @@ +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. + + 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. + + .EXAMPLE + Test-MtDefenderAdvancedHuntingAvailable + + Returns $true on a tenant whose Defender for Endpoint tables are served by advanced hunting. + #> + [CmdletBinding()] + [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 + # 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)" + $__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 new file mode 100644 index 0000000000..f1789972be --- /dev/null +++ b/powershell/tests/functions/Test-MtDefenderAdvancedHuntingAvailable.Tests.ps1 @@ -0,0 +1,91 @@ +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 + } + + 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' }) } + + 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, 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 + Should -Invoke -ModuleName Maester Invoke-MtGraphSecurityQuery -ParameterFilter { + $Query -eq 'DeviceInfo | project DeviceId | take 1' + } -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' } + + $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..77ca323553 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,39 @@ $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 + } + + 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 + } } 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)