Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
function Get-MtDefenderForCloudAttackPath {
<#
.SYNOPSIS
Returns the Microsoft Defender for Cloud attack paths grouped by path, together with whether
Defender CSPM is enabled on any readable subscription.

.DESCRIPTION
Attack paths are computed by Defender CSPM, so an empty result has two very different meanings:
the plan is off and nothing was ever computed, or the plan is on and the estate genuinely has no
path. The returned object separates them. CspmEnabled comes from the Defender for Cloud pricing of
CloudPosture, which Azure Resource Graph exposes as microsoft.security/pricings, so the caller can
report "not licensed" instead of a pass.

On the fields, measured against a live Defender CSPM subscription rather than assumed:

- properties.attackPathType is a GUID and properties.displayName is a sentence. The engine
requires an instance ID matching ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$, so the GUID is the ID of
the path type and the sentence is the title. Grouping by the GUID is also what "one result per
attack path type" means: the sentence can repeat across occurrences of the same type.
- properties.entryPoint carries entityInternalId, entityType and dataSource, and no entity name,
so the entry point is reported by its resource type.
- properties.target does carry entityName as well as entityType, so the target is named.
- properties.riskFactors and properties.mITRETacticsAndTechniques.tactics are arrays. Azure
Resource Graph does not support mv-apply, so they are carried as their JSON text and parsed
here.

.EXAMPLE
Get-MtDefenderForCloudAttackPath

Returns whether Defender CSPM is on and the attack paths grouped by path.
#>
[CmdletBinding()]
[OutputType([pscustomobject])]
param()

# Defender CSPM is the plan that computes attack paths. Its pricing row is the only way to tell an
# estate with no path from a subscription that never had the plan on.
$pricingQuery = @'
securityresources
| where type == "microsoft.security/pricings"
| where name == "CloudPosture"
| summarize StandardCount = countif(tostring(properties.pricingTier) == "Standard")
'@

Write-Verbose 'Checking whether Defender CSPM is enabled...'
$pricing = @(Invoke-MtAzureResourceGraphRequest -Query $pricingQuery) | Select-Object -First 1
$cspmEnabled = $null -ne $pricing -and [int]($pricing.StandardCount) -gt 0

$pathQuery = @'
securityresources
| where type == "microsoft.security/attackpaths"
| extend displayName = tostring(properties.displayName),
risk = tostring(properties.riskLevel),
parcial = tostring(properties.isPartialAttackPath),
riskFactors = tostring(properties.riskFactors),
tactics = tostring(properties.mITRETacticsAndTechniques.tactics),
tipoEntrada = tostring(properties.entryPoint.entityType),
targetName = tostring(properties.target.entityName),
tipoDestino = tostring(properties.target.entityType)
// A risk level is per occurrence, so a group holds several. any() picked one at random, and it
// picked independently for the risk factors and the tactics, so the three could describe different
// occurrences of the same attack path type. arg_max takes all three from the one that ranks worst.
| extend riskRank = case(risk =~ "Critical", 4, risk =~ "High", 3, risk =~ "Medium", 2, risk =~ "Low", 1, 0)
| summarize PathCount = count(),
DisplayName = any(displayName),
Partial = any(parcial),
EntryPointTypeList = make_set(tipoEntrada, 10),
TargetList = make_set(targetName, 10),
// make_set is capped, so the consumer needs to know when it is showing a subset.
TargetTotal = dcount(targetName),
TargetTypeList = make_set(tipoDestino, 10),
(RiskRank, RiskLevel, RiskFactorsJson, TacticsJson) = arg_max(riskRank, risk, riskFactors, tactics)
by AttackPathType = tostring(properties.attackPathType)
| project-away RiskRank
| sort by PathCount desc, AttackPathType asc
'@

Write-Verbose 'Querying Defender for Cloud attack paths...'
$rows = @(Invoke-MtAzureResourceGraphRequest -Query $pathQuery)

$paths = [System.Collections.Generic.List[pscustomobject]]::new()
foreach ($row in $rows) {
if (-not $row -or [string]::IsNullOrWhiteSpace([string]$row.AttackPathType)) { continue }
$paths.Add([pscustomobject]@{
AttackPathType = [string]$row.AttackPathType
DisplayName = [string]$row.DisplayName
RiskLevel = [string]$row.RiskLevel
PathCount = [int]($row.PathCount)
RiskFactorList = ConvertFrom-MtJsonArray -Text ([string]$row.RiskFactorsJson)
TacticList = ConvertFrom-MtJsonArray -Text ([string]$row.TacticsJson)
EntryPointTypeList = @($row.EntryPointTypeList | Where-Object { $_ })
TargetList = @($row.TargetList | Where-Object { $_ })
# make_set is capped at 10; this is how many distinct targets there really are.
TargetTotal = [int]($row.TargetTotal)
TargetTypeList = @($row.TargetTypeList | Where-Object { $_ })
})
}

[pscustomobject]@{
CspmEnabled = $cspmEnabled
PathList = $paths
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
function Get-MtDefenderForCloudRecommendation {
<#
.SYNOPSIS
Returns one row per Microsoft Defender for Cloud recommendation across the subscriptions the
signed-in account can read, with how many resources are healthy, unhealthy, not applicable and
exempt.

.DESCRIPTION
Runs a single Azure Resource Graph query over securityresources, aggregated server side so the
result is one row per recommendation rather than one row per resource and recommendation. A large
estate produces thousands of assessment rows and only hundreds of recommendations, which is the
difference the caller needs to stay readable.

Each row carries the recommendation's assessment key, display name, severity from its metadata, the
risk level Defender CSPM adds when it is enabled, the portal link, the resource counts, a capped
sample of the unhealthy resource names, and the exemption cause when every resource is exempt.

An empty result means Defender for Cloud produced no assessment for these subscriptions. The caller
must skip in that case: no unhealthy resource over no assessment is not a pass.

Errors are deliberately not caught here, so a failed query surfaces instead of being read as a
clean estate.

.EXAMPLE
Get-MtDefenderForCloudRecommendation

Returns the Defender for Cloud recommendations with their resource counts.
#>
[CmdletBinding()]
[OutputType([System.Collections.Generic.List[pscustomobject]])]
param()

# Aggregated server side: one row per assessment key. make_set is capped because a recommendation
# can be unhealthy on thousands of resources and the result is a summary, not an inventory.
$query = @'
securityresources
| where type == "microsoft.security/assessments"
Comment thread
earbona23 marked this conversation as resolved.
Resolved
// Multicloud connectors surface AWS and GCP assessments in the same table, and their counts
// would flow into an Azure test. Native Azure resources have no Source, so the empty string is
// kept deliberately: filtering on Source == "Azure" alone would return nothing.
| extend source = tostring(properties.resourceDetails.Source)
| where source == "" or source =~ "Azure"
| extend status = tostring(properties.status.code),
causa = tostring(properties.status.cause),
displayName = tostring(properties.displayName),
severity = tostring(properties.metadata.severity),
risk = tostring(properties.risk.level),
portal = tostring(properties.links.azurePortal)
// A risk level is per resource, so a group holds several. any() picks one at random and could
// report Low for a key that is Critical somewhere. Ranked and maxed, the group reports its worst.
| extend riskRank = case(risk =~ "Critical", 4, risk =~ "High", 3, risk =~ "Medium", 2, risk =~ "Low", 1, 0)
| summarize TotalCount = count(),
UnhealthyCount = countif(status == "Unhealthy"),
HealthyCount = countif(status == "Healthy"),
NotApplicableCount = countif(status == "NotApplicable"),
ExemptCount = countif(causa == "Exempt"),
UnhealthyResourceList = make_set_if(tostring(split(id, "/")[8]), status == "Unhealthy", 10),
UnhealthyResourceTotal = dcountif(tostring(split(id, "/")[8]), status == "Unhealthy"),
// any() is correct for these three: they belong to the assessment definition, so they
// are the same on every row of the group.
DisplayName = any(displayName),
Severity = any(severity),
PortalUri = any(portal),
RiskRank = max(riskRank)
by AssessmentKey = name
| extend RiskLevel = case(RiskRank == 4, "Critical", RiskRank == 3, "High", RiskRank == 2, "Medium", RiskRank == 1, "Low", "")
| project-away RiskRank
| sort by UnhealthyCount desc, AssessmentKey asc
'@

Write-Verbose 'Querying Defender for Cloud assessments through Azure Resource Graph...'
$rows = @(Invoke-MtAzureResourceGraphRequest -Query $query)

$result = [System.Collections.Generic.List[pscustomobject]]::new()
foreach ($row in $rows) {
if (-not $row -or [string]::IsNullOrWhiteSpace([string]$row.AssessmentKey)) { continue }
$result.Add([pscustomobject]@{
AssessmentKey = [string]$row.AssessmentKey
DisplayName = [string]$row.DisplayName
Severity = [string]$row.Severity
RiskLevel = [string]$row.RiskLevel
PortalUri = [string]$row.PortalUri
TotalCount = [int]($row.TotalCount)
UnhealthyCount = [int]($row.UnhealthyCount)
HealthyCount = [int]($row.HealthyCount)
NotApplicableCount = [int]($row.NotApplicableCount)
ExemptCount = [int]($row.ExemptCount)
UnhealthyResourceList = @($row.UnhealthyResourceList)
# The list above is capped at 10, so the caller can say "10 of 37" instead of
# showing a subset as if it were the whole set.
UnhealthyResourceTotal = [int]($row.UnhealthyResourceTotal)
})
}

# -NoEnumerate keeps an empty list from collapsing to $null.
Write-Output $result -NoEnumerate
}
25 changes: 25 additions & 0 deletions powershell/internal/utility/ConvertFrom-MtJsonArray.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
function ConvertFrom-MtJsonArray {
<#
.SYNOPSIS
Reads a JSON array that arrived as text and returns its items, or an empty array.

.DESCRIPTION
Azure Resource Graph has no `mv-apply`, so a query that needs to return an array packs it
into a JSON string. This unpacks it. Empty, whitespace and malformed text all return an
empty array rather than throwing: the caller is building a report row, and a value it
cannot parse is a missing value, not a reason to fail the check.

.EXAMPLE
ConvertFrom-MtJsonArray -Text '["a","b"]'

Returns a and b.
#>
[CmdletBinding()]
[OutputType([object[]])]
param(
[string] $Text
)

if ([string]::IsNullOrWhiteSpace($Text)) { return @() }
try { return @($Text | ConvertFrom-Json) } catch { return @() }
}
12 changes: 9 additions & 3 deletions powershell/tests/fixtures/golden/selection.json
Original file line number Diff line number Diff line change
Expand Up @@ -1951,7 +1951,7 @@
"AD"
]
},
"SelectedCount": 609,
"SelectedCount": 611,
"SelectedFamilies": [
"MT.1024",
"MT.1059",
Expand Down Expand Up @@ -2500,6 +2500,8 @@
"MT.1259",
"MT.1260",
"MT.1265",
"MT.1271",
"MT.1272",
"ORCA.100",
"ORCA.101",
"ORCA.102",
Expand Down Expand Up @@ -2581,7 +2583,7 @@
"AD"
]
},
"SelectedCount": 639,
"SelectedCount": 641,
"SelectedFamilies": [
"MT.1024",
"MT.1033",
Expand Down Expand Up @@ -3162,6 +3164,8 @@
"MT.1259",
"MT.1260",
"MT.1265",
"MT.1271",
"MT.1272",
"ORCA.100",
"ORCA.101",
"ORCA.102",
Expand Down Expand Up @@ -4006,7 +4010,7 @@
"AD"
]
},
"SelectedCount": 595,
"SelectedCount": 597,
"SelectedFamilies": [
"MT.1024",
"MT.1033",
Expand Down Expand Up @@ -4543,6 +4547,8 @@
"MT.1259",
"MT.1260",
"MT.1265",
"MT.1271",
"MT.1272",
"ORCA.100",
"ORCA.101",
"ORCA.102",
Expand Down
Loading
Loading