-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEntraAppRole-AuthCodeFix.ps1
More file actions
142 lines (128 loc) · 7.09 KB
/
EntraAppRole-AuthCodeFix.ps1
File metadata and controls
142 lines (128 loc) · 7.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<#
.SYNOPSIS
Unified ConsentFix mitigation script for identify, enforce, validate, and orchestrated execution.
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)]
[ValidateSet("Identify","Enforce","Validate","RunAll")]
[string]$Mode,
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]$GroupDisplayName,
[Parameter(Mandatory = $false)]
[ValidateSet("baseline-dev-tools", "strict-admin-only")]
[string]$ProfileName = "baseline-dev-tools",
[Parameter(Mandatory = $false)]
[string[]]$IncludeAppIds = @(),
[Parameter(Mandatory = $false)]
[string[]]$ExcludeAppIds = @(),
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]$TargetsFilePath = (Join-Path -Path $PSScriptRoot -ChildPath "AppTargets-AuthCodeFix.json"),
[Parameter(Mandatory = $false)]
[switch]$Transcript,
[Parameter(Mandatory = $false)]
[string]$TranscriptPath = (Join-Path -Path $PSScriptRoot -ChildPath ("ConsentFix-Run-{0:yyyyMMdd-HHmmss}.log" -f (Get-Date)))
)
function Get-AppsFromProfile {
param([string]$Path,[string]$Profile,[string[]]$Include,[string[]]$Exclude)
if (-not (Test-Path -LiteralPath $Path)) { throw "Targets file not found: $Path" }
$config = Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json -ErrorAction Stop
if (-not $config.profiles.PSObject.Properties.Name.Contains($Profile)) {
throw "Profile '$Profile' not found."
}
$map = @{}
foreach ($p in $config.profiles.$Profile.apps.PSObject.Properties) { $map[$p.Name] = [string]$p.Value }
foreach ($id in $Include) { if (-not $map.ContainsKey($id)) { $map[$id] = "Custom include" } }
foreach ($id in $Exclude) { if ($map.ContainsKey($id)) { $map.Remove($id) } }
if ($map.Count -eq 0) { throw "No app IDs remain after include/exclude processing." }
return $map
}
function Connect-GraphForMode {
param([string]$SelectedMode)
$scopes = switch ($SelectedMode) {
"Identify" { @("Application.Read.All","Directory.Read.All") }
"Validate" { @("Application.Read.All","Directory.Read.All") }
default { @("Application.ReadWrite.All","AppRoleAssignment.ReadWrite.All","Group.ReadWrite.All") }
}
Connect-MgGraph -Scopes $scopes -NoWelcome -ErrorAction Stop
}
function Invoke-Identify {
param([hashtable]$AppMap)
$results = foreach ($appId in $AppMap.Keys) {
$filter = "AppId eq '$appId'"
$status = "Unknown"; $cmdStatus = "Failed"; $objectId = $null; $matches = 0
try {
$sp = Get-MgServicePrincipal -Filter $filter -ConsistencyLevel eventual -All -ErrorAction Stop
$cmdStatus = "Succeeded"
if ($sp) { $status = "Exists"; $matches = @($sp).Count; $objectId = ($sp | Select-Object -First 1).Id } else { $status = "Missing" }
} catch { }
[PSCustomObject]@{ Name=$AppMap[$appId]; AppId=$appId; SP_Status=$status; Cmd_Status=$cmdStatus; Matches=$matches; ObjectId=$objectId }
}
$results | Sort-Object SP_Status, Name | Format-Table -AutoSize
}
function Invoke-Enforce {
param([hashtable]$AppMap,[string]$TargetGroup)
if ([string]::IsNullOrWhiteSpace($TargetGroup)) { throw "-GroupDisplayName is required for Enforce/RunAll." }
$group = Get-MgGroup -Filter "displayName eq '$($TargetGroup -replace "'","''")'" -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $group) {
if ($PSCmdlet.ShouldProcess("Group($TargetGroup)", "Create")) {
$mailNick = (($TargetGroup -replace '[^a-zA-Z0-9]', '') + "-" + [guid]::NewGuid().ToString('N').Substring(0,8))
$group = New-MgGroup -DisplayName $TargetGroup -MailEnabled:$false -MailNickname $mailNick.Substring(0,[Math]::Min(64,$mailNick.Length)) -SecurityEnabled:$true -Description "Grants access to locked-down Microsoft CLI/dev tools service principals." -ErrorAction Stop
}
}
if (-not $group) { throw "Group '$TargetGroup' was not created/found." }
foreach ($appId in $AppMap.Keys) {
$sp = Get-MgServicePrincipal -Filter "appId eq '$appId'" -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $sp -and $PSCmdlet.ShouldProcess("ServicePrincipal($appId)", "Create")) {
New-MgServicePrincipal -AppId $appId -ErrorAction Stop | Out-Null
Start-Sleep -Seconds 2
$sp = Get-MgServicePrincipal -Filter "appId eq '$appId'" -ErrorAction SilentlyContinue | Select-Object -First 1
}
if (-not $sp) { Write-Host "Skipping appId $appId (SP unavailable)." -ForegroundColor Yellow; continue }
if ($PSCmdlet.ShouldProcess("ServicePrincipal($($sp.DisplayName))", "Set AppRoleAssignmentRequired=true")) {
Update-MgServicePrincipal -ServicePrincipalId $sp.Id -AppRoleAssignmentRequired:$true -ErrorAction Stop
}
$existing = Get-MgServicePrincipalAppRoleAssignedTo -ServicePrincipalId $sp.Id -Filter "principalId eq $($group.Id)" -All -ErrorAction SilentlyContinue
if (-not $existing -and $PSCmdlet.ShouldProcess("Assignment($($group.DisplayName) -> $($sp.DisplayName))", "Create")) {
New-MgServicePrincipalAppRoleAssignedTo -ServicePrincipalId $sp.Id -PrincipalId $group.Id -ResourceId $sp.Id -AppRoleId "00000000-0000-0000-0000-000000000000" -ErrorAction Stop | Out-Null
}
}
}
function Invoke-Validate {
param([hashtable]$AppMap)
$results = foreach ($appId in $AppMap.Keys) {
$sp = Get-MgServicePrincipal -Filter "appId eq '$appId'" -Top 1 -ErrorAction SilentlyContinue
if (-not $sp) { continue }
$assignedTo = Get-MgServicePrincipalAppRoleAssignedTo -ServicePrincipalId $sp.Id -All -ErrorAction SilentlyContinue
if (-not $assignedTo) {
[PSCustomObject]@{ ResourceDisplayName=$sp.DisplayName; ResourceAppId=$sp.AppId; AssignmentRequired=$sp.AppRoleAssignmentRequired; PrincipalType="<none>"; PrincipalDisplayName="<No assignments found>" }
continue
}
foreach ($a in ($assignedTo | Sort-Object PrincipalType, PrincipalDisplayName)) {
[PSCustomObject]@{ ResourceDisplayName=$sp.DisplayName; ResourceAppId=$sp.AppId; AssignmentRequired=$sp.AppRoleAssignmentRequired; PrincipalType=$a.PrincipalType; PrincipalDisplayName=$a.PrincipalDisplayName }
}
}
$results | Format-Table -AutoSize
}
$startTranscript = $Transcript -or $Mode -eq 'RunAll'
if ($startTranscript) { Start-Transcript -Path $TranscriptPath | Out-Null }
try {
$appMap = Get-AppsFromProfile -Path $TargetsFilePath -Profile $ProfileName -Include $IncludeAppIds -Exclude $ExcludeAppIds
Connect-GraphForMode -SelectedMode $Mode
switch ($Mode) {
"Identify" { Invoke-Identify -AppMap $appMap }
"Enforce" { Invoke-Enforce -AppMap $appMap -TargetGroup $GroupDisplayName }
"Validate" { Invoke-Validate -AppMap $appMap }
"RunAll" {
Invoke-Identify -AppMap $appMap
Invoke-Enforce -AppMap $appMap -TargetGroup $GroupDisplayName
Invoke-Validate -AppMap $appMap
}
}
}
finally {
Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null
if ($startTranscript) { Stop-Transcript | Out-Null }
}