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
1 change: 1 addition & 0 deletions powershell/Maester.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
'Get-MtAuthenticationMethodPolicyConfig',
'Get-MtAzureManagementGroup',
'Get-MtConditionalAccessPolicy',
'Get-MtConditionalAccessPolicyPlan',
'Get-MtConnectionState',
'Get-MtConnector',
'Get-MtExo',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,20 @@

See [Plan a Conditional Access deployment - Microsoft Learn](https://learn.microsoft.com/entra/identity/conditional-access/plan-conditional-access#apply-conditional-access-policies-to-every-app)'
if ($SkipCheckAllUsers.IsPresent) {
$testResult = "These Conditional Access policies target all cloud apps:`n`n"
$testResult = "These Conditional Access policies target all cloud apps:`n`n%TestResult%"
} else {
$testResult = "These Conditional Access policies target all cloud apps and all users:`n`n"
$testResult = "These Conditional Access policies target all cloud apps and all users:`n`n%TestResult%"
}

$matchingPolicies = [System.Collections.Generic.List[object]]::new()
$result = $false
foreach ($policy in $policies) {
if ( ( $SkipCheckAllUsers.IsPresent -or $policy.conditions.users.includeUsers -eq 'All' ) `
-and $policy.conditions.applications.includeApplications -eq 'All' `
) {
$result = $true
$currentResult = $true
$testResult += " - [$(Get-MtSafeMarkdown $policy.displayName)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/$($($policy.id))?%23view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies?=)`n"
$matchingPolicies.Add($policy)
} else {
$currentResult = $false
}
Expand All @@ -66,7 +67,7 @@
}
}

Add-MtTestResultDetail -Description $testDescription -Result $testResult
Add-MtTestResultDetail -Description $testDescription -Result $testResult -GraphObjects $matchingPolicies.ToArray() -GraphObjectType ConditionalAccess
return $result

}
24 changes: 20 additions & 4 deletions powershell/internal/report/Get-GraphObjectMarkdown.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
# The type of graph object, this will be used to show the right deeplink to the test results report.
# If not specified, the function will try to determine the type based on the object.
[Parameter(Mandatory = $false)]
[ValidateSet('AuthenticationMethod', 'AuthorizationPolicy', 'ConditionalAccess', 'ConsentPolicy',
[ValidateSet('AuthenticationMethod', 'AuthorizationPolicy', 'ConditionalAccess', 'ConditionalAccessPlan', 'ConsentPolicy',
'Devices', 'Domains', 'Groups', 'IdentityProtection', 'Users', 'UserRole'
)]
[string] $GraphObjectType,
Expand Down Expand Up @@ -52,16 +52,32 @@
}

if($currentGraphObjectType) {
$link = $markdownLinkTemplate[$currentGraphObjectType] -f $item.id
if ($currentGraphObjectType -eq 'ConditionalAccess' -and (Get-ObjectProperty $item 'planId')) {
$link = $markdownLinkTemplate.ConditionalAccessPlan -f $item.planId
} else {
$link = $markdownLinkTemplate[$currentGraphObjectType] -f $item.id
}
}
else {
$link = "#"
}

# A plan URL contains only the parent ID. Keep the rule identity in the link title so
# custom Markdown tables and rehydrated reports can recover it without changing the URL.
$linkTitle = ''
if ($currentGraphObjectType -eq 'ConditionalAccess' -and
(Get-ObjectProperty $item 'sourceType') -eq 'PolicyPlanRule' -and
(Get-ObjectProperty $item 'planId')) {
$ruleId = [string](Get-ObjectProperty $item 'id')
if ($ruleId -match '^[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$') {
$linkTitle = ' "ConditionalAccessPolicyRule:{0}"' -f $ruleId
}
}

if ($AsPlainTextLink) {
$result += "[$displayName]($link)"
$result += "[$displayName]($link$linkTitle)"
} else {
$result += " - [$displayName]($link)`n"
$result += " - [$displayName]($link$linkTitle)`n"
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
# Get-MtAffectedObjectFromMarkdown so records from both sources dedupe correctly.
$canonicalType = @{
ConditionalAccess = 'ConditionalAccessPolicy'
ConditionalAccessPlan = 'ConditionalAccessPolicyPlan'
Users = 'User'
UserRole = 'User'
Groups = 'Group'
Expand Down Expand Up @@ -67,12 +68,13 @@
$type = $objectTypeAlias[$type]
}

$isPlanRule = (Get-ObjectProperty $item 'sourceType') -eq 'PolicyPlanRule' -and (Get-ObjectProperty $item 'planId')
$portalLink = $null
if ($type -and $portalLinkTemplate.LinkTemplates.ContainsKey($type)) {
$template = $portalLinkTemplate.LinkTemplates[$type]
# A per-object template without the id would open a broken blade.
if ($id -or -not $template.Contains('{0}')) {
$portalLink = $template -f $id
$portalLink = if ($isPlanRule) { $portalLinkTemplate.LinkTemplates.ConditionalAccessPlan -f $item.planId } else { $template -f $id }
}
}

Expand All @@ -90,7 +92,8 @@
[PSCustomObject]@{
System = 'EntraID'
AnchorKind = $anchorKind
Type = if ($type -and $canonicalType.ContainsKey($type)) { $canonicalType[$type] }
Type = if ($isPlanRule) { 'ConditionalAccessPolicyRule' }
elseif ($type -and $canonicalType.ContainsKey($type)) { $canonicalType[$type] }
elseif ($type) { $type }
elseif ($odataType -and $odataObjectType.ContainsKey($odataType)) { $odataObjectType[$odataType] }
elseif ($odataType) { $odataType }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
`[name](url "title")`), the display name is captured too, with markdown escapes such as
`\(` and `\_` removed. The matched URL is kept as the record's PortalLink.

Plan-rule links can carry a ConditionalAccessPolicyRule:<rule-id> title. For those links the rule ID
identifies the affected object while the unchanged plan URL remains its PortalLink.

Links with an empty target whose text is a user principal name (`[user@contoso.com]()`, as the
Entra recommendation checks write them) are captured as users keyed by that UPN.
#>
Expand All @@ -34,6 +37,7 @@

# Ordered: more specific patterns first. Id = first capture group.
$patterns = @(
@{ System = 'EntraID'; Type = 'ConditionalAccessPolicyPlan'; Regex = "Microsoft_AAD_ConditionalAccess/PolicyPlanView\.ReactView/planId/($guid)" }
@{ System = 'EntraID'; Type = 'ConditionalAccessPolicy'; Regex = "Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/($guid)" }
# The appId suffix is optional: some checks link the enterprise app by object id only.
@{ System = 'EntraID'; Type = 'ServicePrincipal'; Regex = "ManagedAppMenuBlade/~/\w+/objectId/($guid)(?:/appId/$guid)?" }
Expand Down Expand Up @@ -64,9 +68,10 @@
# different occurrence. .NET allows the repeated 'url' group name across the alternation.
# https only: display names are not escaped in result markdown, so a crafted name can smuggle
# a javascript: url into a link that would otherwise match a portal pattern.
# The name may contain one level of brackets ("[RaviK] - Policy") and the url may be followed
# by a link title (`[name](url "title")`).
$linkPattern = '\[(?<name>(?:[^\[\]]|\[[^\[\]]*\])+)\]\((?<url>https://[^)\s]+)(?:\s+"[^"]*")?\)|(?<url>https://[^\s)\]]+)'
# Consume backslash escapes before interpreting brackets. Generated names can contain escaped
# unmatched or nested brackets; legacy unescaped names may contain one bracketed group.
# The url may be followed by a link title (`[name](url "title")`).
$linkPattern = '\[(?<name>(?:\\.|[^\[\]\\]|\[(?:\\.|[^\[\]\\])*\])+)\]\((?<url>https://[^)\s]+)(?:\s+"(?<title>[^"]*)")?\)|(?<url>https://[^\s)\]]+)'
# Markdown backslash escapes (\( \_ \* ...) that result markdown adds around display names.
# Must stay a superset of what Get-MtSafeMarkdown escapes, or a name keeps a literal
# backslash on the affected-objects page. `:` and `@` were added there for GFM autolink
Expand All @@ -86,11 +91,19 @@
$displayName = $link.Groups['name'].Value -replace $markdownEscape, '$1'
}

$type = $pattern.Type
$id = $match.Groups[1].Value
if ($type -eq 'ConditionalAccessPolicyPlan' -and
$link.Groups['title'].Value -match "^ConditionalAccessPolicyRule:($guid)$") {
$type = 'ConditionalAccessPolicyRule'
$id = $Matches[1]
}

$records.Add([PSCustomObject]@{
System = $pattern.System
AnchorKind = 'Instance'
Type = $pattern.Type
Id = $match.Groups[1].Value
Type = $type
Id = $id
DisplayName = $displayName
PortalLink = $url
TestId = $TestId
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
'AuthenticationMethod'
'AuthorizationPolicy'
'ConditionalAccessPolicy'
'ConditionalAccessPolicyPlan'
'ConditionalAccessPolicyRule'
'ConsentPolicy'
'Device'
'DirectoryRole'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
LinkTemplates = @{
AuthenticationMethod = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/AuthenticationMethodsMenuBlade/~/AdminAuthMethods"
AuthorizationPolicy = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_UsersAndTenants/UserManagementMenuBlade/~/UserSettings/menuId/UserSettings"
ConditionalAccessPlan = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_ConditionalAccess/PolicyPlanView.ReactView/planId/{0}"
ConditionalAccess = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/{0}"
ConsentPolicy = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/ConsentPoliciesMenuBlade/~/UserSettings"
Devices = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_Devices/DeviceDetailsMenuBlade/~/Properties/objectId/{0}"
Expand All @@ -31,12 +32,14 @@
}
# @odata.type → GraphObjectType (auto-detection when no explicit type is passed)
OdataTypeMapping = @{
'#microsoft.graph.conditionalAccessPolicyPlan' = 'ConditionalAccessPlan'
'#microsoft.graph.conditionalAccessPolicyRule' = 'ConditionalAccess'
'#microsoft.graph.user' = 'Users'
'#microsoft.graph.group' = 'Groups'
'#microsoft.graph.device' = 'Devices'
}
# GraphObjectType → whether the deep link addresses a single object instance
# (types not listed here resolve to a tenant-level settings surface)
InstanceTypes = @('ConditionalAccess', 'Devices', 'Groups', 'Users', 'UserRole')
InstanceTypes = @('ConditionalAccess', 'ConditionalAccessPlan', 'Devices', 'Groups', 'Users', 'UserRole')
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
function ConvertTo-MtConditionalAccessPolicy {
<#
.SYNOPSIS
Projects a plan rule into the policy shape used by Maester's Conditional Access checks.

.DESCRIPTION
Preserves the real rule ID, state, original rule conditions and controls. Exposes inherited effective conditions,
grantControls and sessionControls at the same paths as a standalone policy, with explicit parent-plan metadata.
Never mutates the cached plan or rule and never treats a plan owner as an administrator or a rule assignment.
#>
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory)] [object] $Plan,
[Parameter(Mandatory)] [object] $Rule
)

if ([string]::IsNullOrWhiteSpace([string]$Plan.id) -or [string]::IsNullOrWhiteSpace([string]$Rule.id)) {
throw 'Conditional Access plans and rules must have IDs before they can be evaluated.'
}
if ($Rule.state -notin @('enabled', 'disabled', 'enabledForReportingButNotEnforced')) {
throw "Conditional Access rule '$($Rule.id)' has an unsupported state '$($Rule.state)'."
}
# Copy only inherited targeting; serializing the sibling rules for each projection is quadratic.
$sharedConditions = ConvertTo-Json -InputObject $Plan.sharedConditions -Depth 100 | ConvertFrom-Json -AsHashtable
$copy = $Rule | ConvertTo-Json -Depth 100 | ConvertFrom-Json -AsHashtable
if (-not $copy.controls -or (-not $copy.controls.grantControls -and -not $copy.controls.sessionControls)) {
throw "Conditional Access rule '$($Rule.id)' has no supported enforcement controls."
}
$copy['@odata.type'] = '#microsoft.graph.conditionalAccessPolicyRule'
$copy['ruleConditions'] = $copy.conditions
try {
$copy['conditions'] = Merge-MtConditionalAccessCondition -Shared $sharedConditions -Rule $copy.conditions
} catch {
throw "Cannot evaluate rule '$($Rule.id)' in plan '$($Plan.id)': $($_.Exception.Message)"
}
$copy['grantControls'] = $copy.controls.grantControls
$copy['sessionControls'] = $copy.controls.sessionControls
$copy['displayName'] = "[Plan: $($Plan.displayName)] [Rule: $($Rule.displayName)]"
$copy['planId'] = $Plan.id
$copy['planDisplayName'] = $Plan.displayName
$copy['planOwners'] = @($Plan.owners)
$copy['sharedConditions'] = $sharedConditions
$copy['sourceType'] = 'PolicyPlanRule'
return [pscustomobject]$copy
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
function Merge-MtConditionalAccessCondition {
<#
.SYNOPSIS
Combines inherited and rule-specific Conditional Access conditions without overwriting exclusions.

.DESCRIPTION
Merges Graph condition dictionaries recursively and unions collection values. Null and empty optional
values do not erase inherited targeting. Incompatible scalar values, including conflicting filter expressions,
terminate the read: inventing a lossy effective policy could make an uncovered scenario pass a security check.
Inputs are JSON-compatible copies owned by the policy adapter, not objects in the Graph session cache.
#>
[CmdletBinding()]
param(
[AllowNull()] [object] $Shared,
[AllowNull()] [object] $Rule,
[string] $PropertyPath = 'conditions'
)

if ($null -eq $Shared) { Write-Output -NoEnumerate -InputObject $Rule; return }
if ($null -eq $Rule) { Write-Output -NoEnumerate -InputObject $Shared; return }

if ($Shared -is [System.Collections.IDictionary] -and $Rule -is [System.Collections.IDictionary]) {
# Guest type and tenant membership form a pair. Unioning both independently invents cross-products
# (type A in tenant X plus type B in tenant Y must not become both types in both tenants).
if ($PropertyPath -match '\.(includeGuestsOrExternalUsers|excludeGuestsOrExternalUsers)$') {
$sharedTypes = @(([string]$Shared.guestOrExternalUserTypes -split ',') | Sort-Object -Unique) -join ','
$ruleTypes = @(([string]$Rule.guestOrExternalUserTypes -split ',') | Sort-Object -Unique) -join ','
# Tenant membership is a set, independent of member order, duplicate IDs or JSON key order.
# Keep a missing scope distinct from both all and an empty enumerated scope.
$tenantScopes = foreach ($condition in @($Shared, $Rule)) {
if ($null -eq $condition.externalTenants) {
'absent'
} else {
[ordered]@{
membershipKind = $condition.externalTenants.membershipKind
members = @($condition.externalTenants.members | Sort-Object -Unique)
} | ConvertTo-Json -Depth 100 -Compress
}
}
if ($sharedTypes -ne $ruleTypes -and $tenantScopes[0] -ne $tenantScopes[1]) {
throw "Cannot safely combine guest types and tenant sets at '$PropertyPath' without broadening the targeting."
}
}
# The all-external-tenants discriminator denotes the union's entire tenant set.
if ($PropertyPath -like '*.externalTenants' -and ($Shared.membershipKind -eq 'all' -or $Rule.membershipKind -eq 'all')) {
$all = if ($Shared.membershipKind -eq 'all') { $Shared } else { $Rule }
Write-Output -NoEnumerate -InputObject $all
return
}
$merged = [ordered]@{}
$keys = @(@($Shared.Keys) + @($Rule.Keys) | Select-Object -Unique)
foreach ($key in $keys) {
if ($key -like '*@odata.context') { continue }
$merged[$key] = Merge-MtConditionalAccessCondition -Shared $Shared[$key] -Rule $Rule[$key] -PropertyPath "$PropertyPath.$key"
}
Write-Output -NoEnumerate -InputObject $merged
return
}

if ($Shared -is [System.Collections.IList] -and $Rule -is [System.Collections.IList]) {
$union = [System.Collections.Generic.List[object]]::new()
$seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
foreach ($value in @($Shared) + @($Rule)) {
$key = ConvertTo-Json -InputObject $value -Depth 100 -Compress
if ($seen.Add($key)) { $union.Add($value) }
}
# These collection properties use All as a wildcard, not an additional narrowing condition.
if ($PropertyPath -match '\.(includeUsers|includeApplications|includePlatforms|includeLocations|clientAppTypes)$') {
$all = @($union | Where-Object { $_ -is [string] -and $_ -eq 'all' })
if ($all.Count -gt 0) { Write-Output -NoEnumerate -InputObject @($all[0]); return }
}
Write-Output -NoEnumerate -InputObject $union.ToArray()
return
}

if ($Shared -is [string] -and [string]::IsNullOrWhiteSpace($Shared)) { Write-Output -NoEnumerate -InputObject $Rule; return }
if ($Rule -is [string] -and [string]::IsNullOrWhiteSpace($Rule)) { Write-Output -NoEnumerate -InputObject $Shared; return }
if (($Shared | ConvertTo-Json -Depth 100 -Compress) -ceq ($Rule | ConvertTo-Json -Depth 100 -Compress)) {
Write-Output -NoEnumerate -InputObject $Shared
return
}
if ($Shared -is [string] -and $Rule -is [string] -and
$PropertyPath -match '\.(guestOrExternalUserTypes|insiderRiskLevels|agentIdRiskLevels|transferMethods)$') {
$flags = @(@($Shared -split ',') + @($Rule -split ',') | ForEach-Object { $_.Trim() } | Where-Object { $_ } | Select-Object -Unique)
return $flags -join ','
}
throw "Cannot safely combine Conditional Access plan and rule values at '$PropertyPath'. The inventory is incomplete; use a scenario evaluation for this condition instead of assuming coverage."
}
2 changes: 1 addition & 1 deletion powershell/public/run/Add-MtTestResultDetail.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
[Object[]] $GraphObjects,

# The type of graph object, this will be used to show the right deep-link to the test results report.
[ValidateSet('AuthenticationMethod', 'AuthorizationPolicy', 'ConditionalAccess', 'ConsentPolicy',
[ValidateSet('AuthenticationMethod', 'AuthorizationPolicy', 'ConditionalAccess', 'ConditionalAccessPlan', 'ConsentPolicy',
'Devices', 'Domains', 'Groups', 'IdentityProtection', 'Users', 'UserRole'
)]
[string] $GraphObjectType,
Expand Down
Loading
Loading