-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEntra-PIM.ps1
More file actions
7559 lines (6532 loc) · 310 KB
/
Entra-PIM.ps1
File metadata and controls
7559 lines (6532 loc) · 310 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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ========================= Script Parameters =========================
param(
[Parameter(HelpMessage = "Client ID of the app registration to use for delegated auth")]
[string]$ClientId,
[Parameter(HelpMessage = "Tenant ID to use with the specified app registration")]
[string]$TenantId
)
# Store parameters at script scope for use in authentication functions
$script:CustomClientId = $ClientId
$script:CustomTenantId = $TenantId
# ========================= Version =========================
$script:Version = "2.3.5"
# ========================= Cross-Platform Keyboard Shortcuts =========================
# Detect if running on macOS (use built-in $IsMacOS variable if available)
$script:IsRunningOnMac = if ($null -ne $IsMacOS) { $IsMacOS } else { $PSVersionTable.OS -match 'Darwin' }
# Enable Ctrl+C as input on macOS/Linux (prevents SIGINT from terminating the script)
# This must be set before any [Console]::ReadKey() calls
if ($script:IsRunningOnMac -or ($null -ne $IsLinux -and $IsLinux)) {
[Console]::TreatControlCAsInput = $true
# Clear any buffered input that may have been queued when setting TreatControlCAsInput
Start-Sleep -Milliseconds 100
while ([Console]::KeyAvailable) {
$null = [Console]::ReadKey($true)
}
}
# Cross-platform shortcut detection
function Test-CancelShortcut {
param([System.ConsoleKeyInfo]$Key)
# Ctrl+C for cancel/exit on all platforms
return ($Key.Key -eq 'C' -and ($Key.Modifiers -band [ConsoleModifiers]::Control))
}
function Test-QuitShortcut {
param([System.ConsoleKeyInfo]$Key)
# Ctrl+Q works on both macOS and Windows
# Also accept Ctrl+C as quit shortcut (especially important for macOS)
return (($Key.Key -eq 'Q' -and ($Key.Modifiers -band [ConsoleModifiers]::Control)) -or
($Key.Key -eq 'C' -and ($Key.Modifiers -band [ConsoleModifiers]::Control)))
}
function Test-HelpShortcut {
param([System.ConsoleKeyInfo]$Key)
if ($script:IsRunningOnMac) {
# On macOS: Ctrl+H sends Backspace with Control modifier
return ($Key.Key -eq 'Backspace' -and ($Key.Modifiers -band [ConsoleModifiers]::Control))
} else {
# On Windows: Ctrl+H works normally
return ($Key.Key -eq 'H' -and ($Key.Modifiers -band [ConsoleModifiers]::Control))
}
}
function Get-HelpShortcutText {
return "Ctrl+H Help"
}
function Get-QuitShortcutText {
return "Ctrl+Q Exit"
}
# ========================= Authentication =========================
# Global variable to store assembly paths
$script:MSALAssemblyPaths = @{}
function Initialize-MSALAssemblies {
<#
.SYNOPSIS
Loads MSAL assemblies for browser-based authentication (no WAM).
#>
# Get user home directory (cross-platform)
$userHome = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME }
# Try to find MSAL from nuget cache first
$nugetPath = Join-Path $userHome ".nuget/packages/microsoft.identity.client"
$msalDll = $null
$abstractionsDll = $null
if (Test-Path $nugetPath) {
# Get latest version
$latestVersion = Get-ChildItem $nugetPath -Directory | Sort-Object Name -Descending | Select-Object -First 1
if ($latestVersion) {
$msalDll = Join-Path $latestVersion.FullName "lib/net6.0/Microsoft.Identity.Client.dll"
if (-not (Test-Path $msalDll)) {
$msalDll = Join-Path $latestVersion.FullName "lib/netstandard2.0/Microsoft.Identity.Client.dll"
}
}
# Find abstractions
$abstractionsPath = Join-Path $userHome ".nuget/packages/microsoft.identitymodel.abstractions"
if (Test-Path $abstractionsPath) {
$latestAbstractions = Get-ChildItem $abstractionsPath -Directory | Sort-Object Name -Descending | Select-Object -First 1
if ($latestAbstractions) {
$abstractionsDll = Join-Path $latestAbstractions.FullName "lib/net6.0/Microsoft.IdentityModel.Abstractions.dll"
if (-not (Test-Path $abstractionsDll)) {
$abstractionsDll = Join-Path $latestAbstractions.FullName "lib/netstandard2.0/Microsoft.IdentityModel.Abstractions.dll"
}
}
}
}
# Fallback to Az.Accounts if nuget not available
if (-not $msalDll -or -not (Test-Path $msalDll)) {
$LoadedAzAccountsModule = Get-Module -Name Az.Accounts
if ($null -eq $LoadedAzAccountsModule) {
$AzAccountsModule = Get-Module -Name Az.Accounts -ListAvailable | Select-Object -First 1
if ($null -eq $AzAccountsModule) {
Write-Verbose "Neither nuget cache nor Az.Accounts module found for MSAL"
return $false
}
Import-Module Az.Accounts -ErrorAction SilentlyContinue -Verbose:$false
}
$LoadedAssemblies = [System.AppDomain]::CurrentDomain.GetAssemblies() | Select-Object -ExpandProperty Location -ErrorAction SilentlyContinue
# Cross-platform regex - match both forward and back slashes
$AzureCommon = $LoadedAssemblies | Where-Object { $_ -match "[/\\]Modules[/\\]Az.Accounts[/\\]" -and $_ -match "Microsoft.Azure.Common" }
if ($AzureCommon) {
$AzureCommonLocation = Split-Path -Parent $AzureCommon
$foundMsal = Get-ChildItem -Path $AzureCommonLocation -Filter "Microsoft.Identity.Client.dll" -Recurse -File -ErrorAction SilentlyContinue | Select-Object -First 1
$foundAbstractions = Get-ChildItem -Path $AzureCommonLocation -Filter "Microsoft.IdentityModel.Abstractions.dll" -Recurse -File -ErrorAction SilentlyContinue | Select-Object -First 1
if ($foundMsal) { $msalDll = $foundMsal.FullName }
if ($foundAbstractions) { $abstractionsDll = $foundAbstractions.FullName }
}
}
if (-not $msalDll -or -not (Test-Path $msalDll)) {
Write-Verbose "Could not find Microsoft.Identity.Client.dll"
return $false
}
# Load assemblies
$loadedAssembliesCheck = [System.AppDomain]::CurrentDomain.GetAssemblies()
# Load abstractions first if available
if ($abstractionsDll -and (Test-Path $abstractionsDll)) {
$alreadyLoaded = $loadedAssembliesCheck | Where-Object { $_.GetName().Name -eq 'Microsoft.IdentityModel.Abstractions' } | Select-Object -First 1
if (-not $alreadyLoaded) {
try {
[void][System.Reflection.Assembly]::LoadFrom($abstractionsDll)
$script:MSALAssemblyPaths['Microsoft.IdentityModel.Abstractions'] = $abstractionsDll
} catch { }
} else {
$script:MSALAssemblyPaths['Microsoft.IdentityModel.Abstractions'] = $alreadyLoaded.Location
}
}
# Load MSAL
$alreadyLoaded = $loadedAssembliesCheck | Where-Object { $_.GetName().Name -eq 'Microsoft.Identity.Client' } | Select-Object -First 1
if (-not $alreadyLoaded) {
try {
[void][System.Reflection.Assembly]::LoadFrom($msalDll)
$script:MSALAssemblyPaths['Microsoft.Identity.Client'] = $msalDll
} catch {
Write-Verbose "Failed to load MSAL: $_"
return $false
}
} else {
$script:MSALAssemblyPaths['Microsoft.Identity.Client'] = $alreadyLoaded.Location
}
return $true
}
# Global to track if MSAL helper is compiled
$script:MSALHelperCompiled = $false
function Initialize-MSALHelper {
<#
.SYNOPSIS
Pre-compiles the MSAL helper C# code for browser-based authentication.
#>
if ($script:MSALHelperCompiled) { return $true }
# Get referenced assemblies for Add-Type
$referencedAssemblies = @(
$script:MSALAssemblyPaths['Microsoft.IdentityModel.Abstractions'],
$script:MSALAssemblyPaths['Microsoft.Identity.Client']
) | Where-Object { $_ }
if ($referencedAssemblies.Count -lt 1) {
throw "Missing required MSAL assemblies"
}
# Add standard assemblies
$referencedAssemblies += @("netstandard", "System.Linq", "System.Threading.Tasks", "System.Collections")
# C# code for browser-based authentication (no WAM)
$code = @"
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
public class PIMBrowserAuth
{
public static string GetAccessToken(string clientId, string[] scopes, string tenantId = null)
{
return GetAccessTokenWithClaims(clientId, scopes, null, tenantId);
}
public static string GetAccessTokenWithClaims(string clientId, string[] scopes, string claims, string tenantId = null)
{
try
{
var task = Task.Run(async () => await GetAccessTokenAsync(clientId, scopes, claims, tenantId));
if (task.Wait(TimeSpan.FromSeconds(180)))
{
return task.Result;
}
throw new TimeoutException("Authentication timed out");
}
catch (AggregateException ae)
{
if (ae.InnerException != null) throw ae.InnerException;
throw;
}
}
private static async Task<string> GetAccessTokenAsync(string clientId, string[] scopes, string claims, string tenantId)
{
// Use system browser with localhost redirect - must match app registration
var builder = PublicClientApplicationBuilder.Create(clientId)
.WithRedirectUri("http://localhost");
// Add tenant ID if provided (for dedicated app registrations)
// This enforces the tenant at the authority level
if (!string.IsNullOrEmpty(tenantId))
{
builder = builder.WithAuthority($"https://login.microsoftonline.com/{tenantId}");
}
IPublicClientApplication publicClientApp = builder.Build();
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(180)))
{
var webViewOptions = new SystemWebViewOptions
{
HtmlMessageSuccess = @"
<html>
<head>
<meta charset='UTF-8'>
<title>Authentication Successful - Entra PIM</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.container { text-align: center; color: white; }
.brand { font-size: 14px; letter-spacing: 4px; margin-bottom: 30px; opacity: 0.9; }
.version { font-size: 12px; opacity: 0.7; }
.checkmark { font-size: 64px; margin-bottom: 20px; }
h1 { margin: 0 0 10px 0; font-weight: 300; font-size: 28px; }
p { margin: 0; opacity: 0.9; font-size: 16px; }
</style>
</head>
<body>
<div class='container'>
<div class='brand'>[ E N T R A P I M ] <span class='version'>v2.3.5</span></div>
<div class='checkmark'>✓</div>
<h1>Authentication Successful</h1>
<p>You can close this window and return to PowerShell.</p>
<p style='margin-top: 40px; font-size: 12px; opacity: 0.6;'>by Mark Orr</p>
</div>
</body>
</html>",
HtmlMessageError = @"
<html>
<head>
<meta charset='UTF-8'>
<title>Authentication Failed - Entra PIM</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); }
.container { text-align: center; color: white; }
.brand { font-size: 14px; letter-spacing: 4px; margin-bottom: 30px; opacity: 0.9; }
.version { font-size: 12px; opacity: 0.7; }
.icon { font-size: 64px; margin-bottom: 20px; }
h1 { margin: 0 0 10px 0; font-weight: 300; font-size: 28px; }
p { margin: 0; opacity: 0.9; font-size: 16px; }
</style>
</head>
<body>
<div class='container'>
<div class='brand'>[ E N T R A P I M ] <span class='version'>v2.3.5</span></div>
<div class='icon'>✕</div>
<h1>Authentication Failed</h1>
<p>Please close this window and try again.</p>
<p style='margin-top: 40px; font-size: 12px; opacity: 0.6;'>by Mark Orr</p>
</div>
</body>
</html>"
};
var tokenBuilder = publicClientApp.AcquireTokenInteractive(scopes)
.WithPrompt(Prompt.SelectAccount)
.WithUseEmbeddedWebView(false)
.WithSystemWebViewOptions(webViewOptions);
// Add extra query parameters to hint at the tenant
if (!string.IsNullOrEmpty(tenantId))
{
tokenBuilder = tokenBuilder.WithExtraQueryParameters($"domain_hint={tenantId}");
}
// Add claims challenge if provided (for Conditional Access step-up)
if (!string.IsNullOrEmpty(claims))
{
tokenBuilder = tokenBuilder.WithClaims(claims);
}
var result = await tokenBuilder
.ExecuteAsync(cts.Token)
.ConfigureAwait(false);
return result.AccessToken;
}
}
}
"@
# Check if type already exists
try {
$null = [PIMBrowserAuth]
$script:MSALHelperCompiled = $true
return $true
} catch {
# Type doesn't exist, compile it
}
Add-Type -ReferencedAssemblies $referencedAssemblies -TypeDefinition $code -Language CSharp -ErrorAction Stop -IgnoreWarnings 3>$null
$script:MSALHelperCompiled = $true
return $true
}
function Get-BrowserAccessToken {
<#
.SYNOPSIS
Gets an access token using browser-based authentication (forces fresh passkey auth).
#>
param(
[string[]]$Scopes
)
# Ensure MSAL helper is compiled
if (-not $script:MSALHelperCompiled) {
$null = Initialize-MSALHelper
}
# Use custom ClientId if provided, otherwise use Microsoft's well-known PowerShell public client ID
$clientId = if ($script:CustomClientId) { $script:CustomClientId } else { "14d82eec-204b-4c2f-b7e8-296a70dab67e" }
$tenantId = $script:CustomTenantId # May be null, which is fine
# Build scopes string for Graph
$scopeArray = $Scopes | ForEach-Object {
if ($_ -notlike "https://*") { "https://graph.microsoft.com/$_" } else { $_ }
}
$accessToken = [PIMBrowserAuth]::GetAccessToken($clientId, $scopeArray, $tenantId)
return $accessToken
}
function Get-BrowserAccessTokenWithClaims {
<#
.SYNOPSIS
Gets an access token with claims challenge for Conditional Access step-up authentication.
#>
param(
[string[]]$Scopes,
[string]$Claims
)
# Ensure MSAL helper is compiled
if (-not $script:MSALHelperCompiled) {
$null = Initialize-MSALHelper
}
# Use custom ClientId if provided, otherwise use Microsoft's well-known PowerShell public client ID
$clientId = if ($script:CustomClientId) { $script:CustomClientId } else { "14d82eec-204b-4c2f-b7e8-296a70dab67e" }
$tenantId = $script:CustomTenantId # May be null, which is fine
# Build scopes string for Graph
$scopeArray = $Scopes | ForEach-Object {
if ($_ -notlike "https://*") { "https://graph.microsoft.com/$_" } else { $_ }
}
$accessToken = [PIMBrowserAuth]::GetAccessTokenWithClaims($clientId, $scopeArray, $Claims, $tenantId)
return $accessToken
}
function Get-AzureBrowserAccessTokenWithClaims {
<#
.SYNOPSIS
Gets an Azure management access token with claims challenge for Conditional Access step-up authentication.
#>
param(
[string]$Claims
)
# Ensure MSAL helper is compiled
if (-not $script:MSALHelperCompiled) {
$null = Initialize-MSALHelper
}
# Azure PowerShell client ID and management scope
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
$scopes = @("https://management.azure.com/.default")
$tenantId = $script:CustomTenantId # May be null, which is fine
$accessToken = [PIMBrowserAuth]::GetAccessTokenWithClaims($clientId, $scopes, $Claims, $tenantId)
return $accessToken
}
# ========================= Browser Authentication =========================
function Connect-MgGraphWithBrowser {
param(
[string[]]$Scopes
)
try {
# Clear any existing Graph context first
try { Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null } catch { }
# Show which app registration is being used
if ($script:CustomClientId) {
Write-Host "Using custom app registration..." -ForegroundColor Cyan
Write-Host " Client ID: $($script:CustomClientId)" -ForegroundColor Gray
if ($script:CustomTenantId) {
Write-Host " Tenant ID: $($script:CustomTenantId)" -ForegroundColor Gray
}
} else {
Write-Host "Using default Microsoft Graph authentication..." -ForegroundColor Cyan
}
Write-Host "Opening browser for authentication..." -ForegroundColor Cyan
# Use custom MSAL helper for browser auth with forced login
if ($script:MSALHelperCompiled) {
Write-Host "Waiting for authentication response..." -ForegroundColor Yellow
$accessToken = Get-BrowserAccessToken -Scopes $Scopes
if ($accessToken) {
Write-Host "Authentication successful, connecting to Graph..." -ForegroundColor Cyan
$secureToken = ConvertTo-SecureString $accessToken -AsPlainText -Force
Connect-MgGraph -AccessToken $secureToken -NoWelcome -ErrorAction Stop
} else {
throw "Failed to get access token"
}
} else {
throw "MSAL helper not initialized - could not find Microsoft.Identity.Client.dll"
}
$context = Get-MgContext
if ($context) {
Write-Host " Connected" -ForegroundColor Green
return $true
} else {
Write-Host " Connection failed" -ForegroundColor Red
return $false
}
} catch {
Write-Host " $($_.Exception.Message)" -ForegroundColor Red
return $false
}
}
# ========================= Global Variables =========================
# Global cache for role definitions to avoid repeated API calls
if (-not $script:RoleDefinitionCache) {
$script:RoleDefinitionCache = @{}
$script:RoleDefinitionsBatched = $false
}
# Shared schedule instance cache to avoid duplicate API calls
if (-not $script:ScheduleInstanceCache) {
$script:ScheduleInstanceCache = @{}
$script:ScheduleInstanceCacheExpiry = (Get-Date).AddSeconds(30)
}
# CLEANUP: Consolidated Y/N prompt helper function
function Show-YesNoPrompt {
param(
[string]$Question,
[string]$YesAction = "Yes",
[string]$NoAction = "No"
)
[Console]::CursorVisible = $true
$response = Read-PIMInput -Prompt $Question -ControlsText "Y/N to choose | $(Get-QuitShortcutText)"
if ($response) {
$userInput = $response.Trim().ToUpper()
if ($userInput -eq "Y" -or $userInput -eq "YES") {
return "Yes"
} elseif ($userInput -eq "N" -or $userInput -eq "NO") {
return "No"
}
}
return $null
}
# CLEANUP: Consolidated "no workflows available" exit handler
function Show-NoWorkflowsAndWaitForExit {
Write-Host "❌ No role management workflows available." -ForegroundColor Red
Write-Host ""
Write-Host "Check back later when roles are approved or activated." -ForegroundColor Gray
Show-DynamicControlBar
[Console]::CursorVisible = $false
do {
$key = [Console]::ReadKey($true)
if (Test-QuitShortcut -Key $key) {
Invoke-PIMExit -Message "Exiting PIM role management..."
}
# Handle Ctrl+C (especially important for macOS)
if (Test-CancelShortcut -Key $key) {
Invoke-PIMExit -Message "Operation cancelled..."
}
} while ($true)
}
# OPTIMIZATION: Batch load ALL role definitions at once (called once after auth)
function Initialize-RoleDefinitionCache {
if ($script:RoleDefinitionsBatched) {
return # Already loaded
}
try {
Write-Host "📦 Loading role definitions..." -ForegroundColor Cyan -NoNewline
$allRoleDefs = Get-MgRoleManagementDirectoryRoleDefinition -All
$script:RoleDefinitionCache = @{}
foreach ($roleDef in $allRoleDefs) {
$script:RoleDefinitionCache[$roleDef.Id] = $roleDef
}
$script:RoleDefinitionsBatched = $true
Write-Host " ✅ Loaded $($allRoleDefs.Count) definitions" -ForegroundColor Green
} catch {
Write-Host " ⚠️ Failed to batch load, will fetch individually" -ForegroundColor Yellow
$script:RoleDefinitionsBatched = $false
}
}
function Get-CachedRoleDefinition {
param([string]$RoleId)
# Validate input parameter
if ([string]::IsNullOrEmpty($RoleId)) {
return $null
}
# Return cached result if available (from batch load)
if ($script:RoleDefinitionCache.ContainsKey($RoleId)) {
return $script:RoleDefinitionCache[$RoleId]
}
# Fallback: Fetch individually if not in cache (shouldn't happen after batch load)
try {
$roleDefinition = Get-MgRoleManagementDirectoryRoleDefinition -UnifiedRoleDefinitionId $RoleId
$script:RoleDefinitionCache[$RoleId] = $roleDefinition
return $roleDefinition
} catch {
$script:RoleDefinitionCache[$RoleId] = $null
return $null
}
}
function Get-CachedScheduleInstances {
param([string]$CurrentUserId)
# ALWAYS fetch fresh data for deactivation - no caching
# Use REST API for faster response
try {
$uri = "https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignmentScheduleInstances?`$filter=principalId eq '$CurrentUserId' and assignmentType eq 'Activated'&`$select=id,roleDefinitionId,principalId,directoryScopeId,startDateTime,endDateTime"
$response = Invoke-MgGraphRequest -Method GET -Uri $uri -ErrorAction Stop
if ($response -and $response.value) {
# Return objects with proper property names for compatibility
return $response.value | ForEach-Object {
[PSCustomObject]@{
Id = $_.id
RoleDefinitionId = $_.roleDefinitionId
PrincipalId = $_.principalId
DirectoryScopeId = $_.directoryScopeId
StartDateTime = $_.startDateTime
EndDateTime = $_.endDateTime
}
}
}
return @()
} catch {
return @()
}
}
# OPTIMIZATION: Fast active role retrieval for deactivation workflow
function Get-ActiveRolesOptimized {
param([string]$CurrentUserId)
$activeRoles = @()
try {
# Use REST API for faster response - include all fields needed for deactivation
$uri = "https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignmentScheduleInstances?`$filter=principalId eq '$CurrentUserId' and assignmentType eq 'Activated'&`$select=id,roleDefinitionId,principalId,directoryScopeId,startDateTime,endDateTime"
$response = Invoke-MgGraphRequest -Method GET -Uri $uri -ErrorAction Stop
$scheduleInstances = if ($response -and $response.value) { $response.value } else { @() }
# Use pre-loaded role definition cache for instant lookup
foreach ($instance in $scheduleInstances) {
$roleDefinition = Get-CachedRoleDefinition -RoleId $instance.roleDefinitionId
if ($roleDefinition) {
$expirationTime = $null
if ($instance.endDateTime) {
$expirationTime = [DateTime]::Parse($instance.endDateTime, [System.Globalization.CultureInfo]::InvariantCulture).ToLocalTime()
}
$activeRoles += [PSCustomObject]@{
RoleName = $roleDefinition.DisplayName
Assignment = [PSCustomObject]@{
Id = $instance.id
RoleDefinitionId = $instance.roleDefinitionId
PrincipalId = $instance.principalId
DirectoryScopeId = $instance.directoryScopeId
StartDateTime = $instance.startDateTime
EndDateTime = $instance.endDateTime
}
ExpirationTime = $expirationTime
}
}
}
} catch {
$activeRoles = @()
}
return $activeRoles
}
function Get-EligibleRolesOptimized {
param([string]$CurrentUserId)
# Clear schedule instance cache to ensure fresh data
$script:ScheduleInstanceCache = @{}
$script:ScheduleInstanceCacheExpiry = (Get-Date).AddSeconds(30)
$allEligibleRoles = @()
$activeRoleIds = @()
$pendingRoleIds = @()
try {
# Sequential API calls with timing
$swTotal = [System.Diagnostics.Stopwatch]::StartNew()
$sw1 = [System.Diagnostics.Stopwatch]::StartNew()
$eligibilityResponse = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleEligibilityScheduleInstances?`$filter=principalId eq '$CurrentUserId'&`$select=roleDefinitionId,principalId,directoryScopeId" -ErrorAction Stop
$eligibilitySchedules = if ($eligibilityResponse -and $eligibilityResponse.value) { $eligibilityResponse.value } else { @() }
$sw1.Stop()
Write-Host " [E:$($sw1.ElapsedMilliseconds)ms]" -ForegroundColor DarkGray -NoNewline
$sw2 = [System.Diagnostics.Stopwatch]::StartNew()
try {
$activeResponse = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignmentScheduleInstances?`$filter=principalId eq '$CurrentUserId'&`$select=roleDefinitionId,endDateTime,assignmentType" -ErrorAction Stop
$activatedAssignments = if ($activeResponse -and $activeResponse.value) { $activeResponse.value } else { @() }
} catch { $activatedAssignments = @() }
$sw2.Stop()
Write-Host " [A:$($sw2.ElapsedMilliseconds)ms]" -ForegroundColor DarkGray -NoNewline
$sw3 = [System.Diagnostics.Stopwatch]::StartNew()
try {
$pendingResponse = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignmentScheduleRequests?`$filter=principalId eq '$CurrentUserId' and status eq 'PendingApproval'&`$select=roleDefinitionId" -ErrorAction Stop
} catch { $pendingResponse = $null }
$sw3.Stop()
Write-Host " [P:$($sw3.ElapsedMilliseconds)ms]" -ForegroundColor DarkGray -NoNewline
# Process eligibility schedules with cached role definitions
$sw4 = [System.Diagnostics.Stopwatch]::StartNew()
foreach ($schedule in $eligibilitySchedules) {
$roleDef = Get-CachedRoleDefinition -RoleId $schedule.roleDefinitionId
if ($roleDef) {
$allEligibleRoles += [PSCustomObject]@{
RoleDefinitionId = $schedule.roleDefinitionId
RoleDefinition = @{
DisplayName = $roleDef.DisplayName
Id = $roleDef.Id
Description = $roleDef.Description
}
PrincipalId = $schedule.principalId
DirectoryScopeId = $schedule.directoryScopeId
}
}
}
$sw4.Stop()
Write-Host " [C:$($sw4.ElapsedMilliseconds)ms]" -ForegroundColor DarkGray -NoNewline
# Process active and permanently assigned roles
$activeRoleIds = @()
if ($activatedAssignments -and $activatedAssignments.Count -gt 0) {
$currentTime = Get-Date
$activeRoleIds = $activatedAssignments | Where-Object {
# Exclude permanent assignments (Assigned) and currently active PIM-activated roles
$_.assignmentType -eq 'Assigned' -or
($null -ne $_.endDateTime -and [DateTime]::Parse($_.endDateTime, [System.Globalization.CultureInfo]::InvariantCulture).ToLocalTime() -gt $currentTime)
} | Select-Object -ExpandProperty roleDefinitionId -Unique
}
# Process pending requests
$pendingRoleIds = @()
if ($pendingResponse -and $pendingResponse.value) {
$pendingRoleIds = @($pendingResponse.value | Select-Object -ExpandProperty roleDefinitionId -Unique)
}
$swTotal.Stop()
Write-Host " [T:$($swTotal.ElapsedMilliseconds)ms]" -ForegroundColor DarkGray
} catch {
Write-Host " Err: $($_.Exception.Message)" -ForegroundColor Red
$allEligibleRoles = @()
}
# Filter out both active and pending roles
$eligibleRoles = $allEligibleRoles | Where-Object {
$activeRoleIds -notcontains $_.RoleDefinitionId -and $pendingRoleIds -notcontains $_.RoleDefinitionId
}
# Deduplicate roles by RoleDefinitionId to prevent duplicates
$validRoles = $eligibleRoles | Sort-Object RoleDefinitionId | Group-Object RoleDefinitionId | ForEach-Object { $_.Group[0] }
return $validRoles
}
# ========================= Help Menu =========================
function Show-HelpMenu {
[Console]::CursorVisible = $false
Clear-Host
Write-Host "[ E N T R A P I M ]" -ForegroundColor Magenta
Write-Host ""
Write-Host "📖 Help Menu" -ForegroundColor Cyan
Write-Host ""
Write-Host "SHORTCUTS" -ForegroundColor Yellow
Write-Host " ↑/↓ Navigate SPACE Toggle Ctrl+A Select All ENTER Confirm"
Write-Host " ESC Cancel $(Get-QuitShortcutText) $(Get-HelpShortcutText)"
Write-Host ""
Write-Host "WORKFLOWS" -ForegroundColor Yellow
Write-Host " Activate Roles - Request temporary elevated permissions"
Write-Host " Deactivate Roles - End active role sessions early"
Write-Host ""
Write-Host "INDICATORS" -ForegroundColor Yellow
Write-Host " [✓] Selected [ ] Not selected ► Current item"
Write-Host ""
Write-Host "NOTES" -ForegroundColor Yellow
Write-Host " • Roles must be active 5 min before deactivation"
Write-Host " • Minimum activation duration is 5 minutes"
Write-Host " • Justification required for all activations"
Write-Host " • If requested duration exceeds policy max, each role/group"
Write-Host " activates for its individual policy maximum"
Write-Host ""
Write-Host "Press any key to return..." -ForegroundColor Magenta
$null = [Console]::ReadKey($true)
}
function Show-DynamicExpirationMenu {
param(
[array]$RoleExpirationData,
[string]$Title
)
[Console]::CursorVisible = $false
$currentIndex = 0
$selected = @()
for ($i = 0; $i -lt $RoleExpirationData.Count; $i++) {
$selected += $false
}
try {
do {
Clear-Host
Show-PIMGlobalHeaderMinimal
Write-Host ""
Write-Host $Title -ForegroundColor Cyan
Write-Host ""
# Filter out expired roles and check if any remain
$activeRoleData = @()
$activeSelected = @()
for ($i = 0; $i -lt $RoleExpirationData.Count; $i++) {
$roleData = $RoleExpirationData[$i]
$role = $roleData.Role
$expirationTime = $roleData.ExpirationTime
# Calculate countdown
$isExpired = $false
if ($expirationTime) {
$timeRemaining = $expirationTime - (Get-Date)
if ($timeRemaining.TotalSeconds -gt 0) {
$hours = [Math]::Floor($timeRemaining.TotalHours)
$minutes = $timeRemaining.Minutes
$seconds = $timeRemaining.Seconds
if ($hours -gt 0) {
$countdownText = "expires in ${hours}h ${minutes}m ${seconds}s"
} else {
$countdownText = "expires in ${minutes}m ${seconds}s"
}
} else {
$countdownText = "expired"
$isExpired = $true
}
} else {
$countdownText = "no expiration data"
}
# Only include non-expired roles
if (-not $isExpired) {
$activeRoleData += @{
Role = $role
ExpirationTime = $expirationTime
CountdownText = $countdownText
OriginalIndex = $i
}
$activeSelected += $selected[$i]
}
}
# Check if all roles expired during countdown
if ($activeRoleData.Count -eq 0) {
Clear-Host
Show-PIMGlobalHeaderMinimal
Write-Host ""
Write-Host "ℹ️ No active roles to deactivate at this time." -ForegroundColor Gray
Write-Host ""
Write-Host "Would you like to activate roles instead? (Y/N): " -NoNewline -ForegroundColor Cyan
Write-Host ""
Write-Host ""
Write-Host "Ctrl+Q to exit" -ForegroundColor Magenta
# Ask if user wants to manage more roles
do {
[Console]::SetCursorPosition(42, [Console]::CursorTop - 2)
[Console]::CursorVisible = $true
$userInput = Read-Host
$userInput = $userInput.Trim().ToUpper()
if ($userInput -eq "Y" -or $userInput -eq "YES") {
[Console]::CursorVisible = $true
Start-PIMRoleManagement -CurrentUserId $script:CurrentUserId
return
} elseif ($userInput -eq "N" -or $userInput -eq "NO") {
Show-NoWorkflowsAndWaitForExit
return
} else {
Write-Host "Please enter Y or N." -ForegroundColor Yellow
}
} while ($true)
}
# Update arrays to only include active roles
$selected = $activeSelected
# Calculate total display items (roles + back item)
$backIndex = $activeRoleData.Count
$totalDisplayItems = $activeRoleData.Count + 1
if ($currentIndex -ge $totalDisplayItems) {
$currentIndex = $totalDisplayItems - 1
}
# Display active roles with dynamic countdown
for ($i = 0; $i -lt $activeRoleData.Count; $i++) {
$roleInfo = $activeRoleData[$i]
# Display role with selection indicator
$checkbox = if ($selected[$i]) { "[✓]" } else { "[ ]" }
$arrow = if ($i -eq $currentIndex) { "► " } else { " " }
Write-Host "$arrow$checkbox $($roleInfo.Role.RoleName) ($($roleInfo.CountdownText))" -ForegroundColor $(if ($i -eq $currentIndex) { "Yellow" } else { "White" })
}
# Show Back item
$backArrow = if ($currentIndex -eq $backIndex) { "► " } else { " " }
$backColor = if ($currentIndex -eq $backIndex) { "Yellow" } else { "Gray" }
Write-Host "$backArrow← Back" -ForegroundColor $backColor
Write-Host ""
$selectedCount = ($selected | Where-Object { $_ }).Count
Write-Host "Roles Selected: $selectedCount" -ForegroundColor Green
Write-Host ""
Write-Host "↑/↓ Navigate | SPACE Toggle | Ctrl+A Select All | ENTER Confirm | $(Get-HelpShortcutText) | $(Get-QuitShortcutText)" -ForegroundColor Magenta
# Handle input with timeout for countdown updates
$inputAvailable = $false
$timeout = 1000 # 1 second timeout
$startTime = Get-Date
while (((Get-Date) - $startTime).TotalMilliseconds -lt $timeout -and -not $inputAvailable) {
if ([Console]::KeyAvailable) {
$inputAvailable = $true
break
}
Start-Sleep -Milliseconds 50
}
if ($inputAvailable) {
$key = [Console]::ReadKey($true)
switch ($key.Key) {
"UpArrow" {
if ($currentIndex -gt 0) { $currentIndex-- } else { $currentIndex = $totalDisplayItems - 1 }
}
"DownArrow" {
if ($currentIndex -lt ($totalDisplayItems - 1)) { $currentIndex++ } else { $currentIndex = 0 }
}
"Spacebar" {
if ($currentIndex -eq $backIndex) {
return "BACK"
}
$selected[$currentIndex] = -not $selected[$currentIndex]
}
"Enter" {
if ($currentIndex -eq $backIndex) {
return "BACK"
}
$selectedIndices = @()
for ($i = 0; $i -lt $selected.Count; $i++) {
if ($selected[$i]) {
$selectedIndices += $i
}
}
# Clear screen before returning to prevent UI overlap
Clear-Host
return $selectedIndices
}
"Escape" {
return "BACK"
}
}
# Handle Ctrl+A to select/deselect all
if ($key.Modifiers -eq "Control" -and $key.Key -eq "A") {
# Check if all are currently selected
$allSelected = ($selected | Where-Object { $_ -eq $true }).Count -eq $selected.Count
# Toggle: if all selected, deselect all; otherwise select all
for ($i = 0; $i -lt $selected.Count; $i++) {
$selected[$i] = -not $allSelected
}
}
# Handle Ctrl+H for help menu
if ($key.Modifiers -eq "Control" -and $key.Key -eq "H") {
Show-HelpMenu
}
# Handle Ctrl+Q
if ($key.Modifiers -eq "Control" -and $key.Key -eq "Q") {
Invoke-PIMExit -Message "Exiting PIM role management..."
}
}
} while ($true)
}
finally {
# Keep cursor hidden - calling code manages visibility
}
}
function Start-RoleDeactivationWorkflowWithCheck {
param([string]$CurrentUserId)
# Show progress while loading
Write-Host ""
Write-Host "🔄 Loading active roles..." -ForegroundColor Cyan -NoNewline
# OPTIMIZED: Get active roles with fast lookup
$activeRoles = Get-ActiveRolesOptimized -CurrentUserId $CurrentUserId
Write-Host " ✅ $($activeRoles.Count) found" -ForegroundColor Green
if ($activeRoles.Count -eq 0) {
Write-Host "ℹ️ No active roles to deactivate at this time." -ForegroundColor Gray
Write-Host ""
# Ask if user wants to activate roles instead
$response = Read-PIMInput -Prompt "Would you like to activate roles instead? (Y/N)" -ForegroundColor Cyan
if ($response) {
$userInput = $response.Trim().ToUpper()
if ($userInput -eq "Y" -or $userInput -eq "YES") {
Clear-Host
Show-PIMGlobalHeaderMinimal
Write-Host ""
Write-Host "🔄 Loading eligible roles..." -ForegroundColor Cyan -NoNewline
$eligibleRoles = Get-EligibleRolesOptimized -CurrentUserId $CurrentUserId
if ($eligibleRoles.Count -gt 0) {
Write-Host " ✅ $($eligibleRoles.Count) found" -ForegroundColor Green
Start-RoleActivationWorkflow -ValidRoles $eligibleRoles -CurrentUserId $CurrentUserId
} else {
Write-Host ""