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/Get-MtDefenderExploitableVulnerability.ps1 b/powershell/internal/services/defender/Get-MtDefenderExploitableVulnerability.ps1 new file mode 100644 index 0000000000..2bd6ddc4a6 --- /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..dbc2e364fc --- /dev/null +++ b/powershell/internal/services/defender/Get-MtDefenderSecureConfigurationAssessment.ps1 @@ -0,0 +1,78 @@ +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 + # $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) + }) + } + + # -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/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/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..468bfc057c 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -1951,7 +1951,7 @@ "AD" ] }, - "SelectedCount": 609, + "SelectedCount": 611, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2500,6 +2500,8 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1269", + "MT.1270", "ORCA.100", "ORCA.101", "ORCA.102", @@ -2581,7 +2583,7 @@ "AD" ] }, - "SelectedCount": 639, + "SelectedCount": 641, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3162,6 +3164,8 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1269", + "MT.1270", "ORCA.100", "ORCA.101", "ORCA.102", @@ -4006,7 +4010,7 @@ "AD" ] }, - "SelectedCount": 595, + "SelectedCount": 597, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4543,6 +4547,8 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1269", + "MT.1270", "ORCA.100", "ORCA.101", "ORCA.102", 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-MtDefenderVulnerabilityManagement.Tests.ps1 b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 new file mode 100644 index 0000000000..1f4a5cf84e --- /dev/null +++ b/powershell/tests/functions/Test-MtDefenderVulnerabilityManagement.Tests.ps1 @@ -0,0 +1,352 @@ +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, + Test-MtDefenderAdvancedHuntingAvailable + + function Get-TestConfiguration { + param( + [string] $Name = 'Enable Microsoft Defender Antivirus', + [int] $Applicable = 10, + [int] $NonCompliant = 0, + # [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]@{ + 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: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, $SkippedCustomReason, $Severity) + + $script:TestResult = $Result + $script:SkippedBecause = $SkippedBecause + $script:SkippedCustomReason = $SkippedCustomReason + $script:Severity = $Severity + } + } + + Context 'Test-MtDefenderDeviceSecurityRecommendation (MT.1269)' { + 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' + } + + # 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' }, + @{ Impact = 7; Expected = 'Medium' }, + @{ Impact = 4; Expected = 'Medium' }, + @{ Impact = 3; Expected = 'Low' }, + @{ Impact = 1; Expected = 'Low' } + )) { + 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 '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 } + + $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 + $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.1269 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.1270)' { + 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 '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 'Custom' + $script:SkippedCustomReason | Should -Match 'no result set' + } + } + + 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 + } + } + + 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' + } + } + + 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 + } + } +} diff --git a/tests/maester/defender/Test.MT.1269.md b/tests/maester/defender/Test.MT.1269.md new file mode 100644 index 0000000000..97364015a2 --- /dev/null +++ b/tests/maester/defender/Test.MT.1269.md @@ -0,0 +1,28 @@ +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. +- **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 + +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.1269.ps1 b/tests/maester/defender/Test.MT.1269.ps1 new file mode 100644 index 0000000000..58adc7ddc5 --- /dev/null +++ b/tests/maester/defender/Test.MT.1269.ps1 @@ -0,0 +1,163 @@ +function Get-MtDefenderDeviceSecurityRecommendationInstance { + <# + .SYNOPSIS + Returns one MT.1269 instance per Defender Vulnerability Management security configuration. + + .DESCRIPTION + 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 + 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() + + # 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) { + # 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 + } + + # 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. + # 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 + Title = "Every device should comply with the Defender recommendation '$name'." + Severity = $severity + 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.1269', + 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', + Service = 'Graph', + License = 'DEFENDER_XDR', + Lifecycle = 'Preview', + 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 + + $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" + $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" + + if (-not [string]::IsNullOrWhiteSpace($configuration.Description)) { + # 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.** $(Get-MtSafeMarkdown $configuration.RiskDescription)`n" + } + $devices = @($configuration.NonCompliantDeviceList | Where-Object { $_ }) + if ($devices.Count -gt 0) { + # 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 { + $testResultMarkdown += "`nWell done. Every device this configuration applies to complies with it." + } + + Add-MtTestResultDetail -Result $testResultMarkdown + return $testResult +} diff --git a/tests/maester/defender/Test.MT.1270.md b/tests/maester/defender/Test.MT.1270.md new file mode 100644 index 0000000000..f17297e591 --- /dev/null +++ b/tests/maester/defender/Test.MT.1270.md @@ -0,0 +1,45 @@ +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. + +## 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 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."`. + +## 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.1270.ps1 b/tests/maester/defender/Test.MT.1270.ps1 new file mode 100644 index 0000000000..1fb11c6c81 --- /dev/null +++ b/tests/maester/defender/Test.MT.1270.ps1 @@ -0,0 +1,121 @@ +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 + #> + # 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.', + Product = 'defender', + Feature = 'exposure-management', + Area = 'devices', + ResourceType = 'Device', + Severity = 'Medium', + UserImpact = 'Medium', + ImplementationCost = 'Medium', + Mitre = 'T1203', + Service = 'Graph', + License = 'DEFENDER_XDR', + Lifecycle = 'Preview', + Author = 'earbona23' + )] + [CmdletBinding()] + [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. + 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 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 + } + + $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) { + # 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) { + # 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." + } + + Add-MtTestResultDetail -Result $testResultMarkdown + return $testResult +}