Repository navigation
feat(azure): Defender for Cloud recommendations and attack paths #2703
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
earbona23
wants to merge
13
commits into
maester365:main
Choose a base branch
from
earbona23:feat/2514-2516-defender-for-cloud
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
9e61ea0
feat(azure): Defender for Cloud recommendations and attack paths (#25…
earbona23 4529a47
fix(MT.1258): ImplementationCost is Medium, not High
earbona23 52698f3
fix(MT.1257, MT.1258): the per-instance severity goes on the instance
earbona23 4feac11
fix(MT.1257, MT.1258): the ResourceType and the Mitre technique of th…
earbona23 c1002ca
fix(MT.1258): ResourceType is AzureResource, like MT.1257
earbona23 ff3ba3c
chore: save the new PowerShell files as UTF-8 with BOM
earbona23 a3aea19
fix(MT.1257,MT.1258): deterministic risk, Azure-only scope, and hones…
earbona23 75e529b
Merge remote-tracking branch 'origin/main' into resolver/2703
earbona23 77fef15
chore: renumber to the next free MT sequence (MT.1257/1258 -> MT.1271…
earbona23 5bbe44f
refactor(azure): English identifiers, own file for the helper, escape…
earbona23 f012c22
style: canonical attribute property order
earbona23 ae0934e
Merge main and regenerate the golden selection fixture
earbona23 08b210a
Merge branch 'main' into feat/2514-2516-defender-for-cloud
earbona23 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
103 changes: 103 additions & 0 deletions
103
powershell/internal/services/azure/Get-MtDefenderForCloudAttackPath.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| } |
97 changes: 97 additions & 0 deletions
97
powershell/internal/services/azure/Get-MtDefenderForCloudRecommendation.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| // 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 | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 @() } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.