-
Notifications
You must be signed in to change notification settings - Fork 18
/
Azure-AccessPermissions.ps1
1944 lines (1805 loc) · 98.7 KB
/
Azure-AccessPermissions.ps1
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
<#
.SYNOPSIS
Script to enumerate access permissions of a user's Azure Active Directory home tenant.
.NOTES
Author: 0xcsandker
Creation Date: 19.10.2022
.EXAMPLE
PS:> . .\Azure-AccessPermissions.ps1
PS:> Invoke-AccessCheckForCurrentUser
.EXAMPLE
PS:> . .\Azure-AccessPermissions.ps1
PS:> Invoke-AccessCheckForAllServicePrincipals
.EXAMPLE
PS:> . .\Azure-AccessPermissions.ps1
PS:> Invoke-AccessCheckForServicePrincipal -ServicePrincipalIdentifier 94fc9712-01e1-4115-ad4e-56a428e438b0
#>
#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Script Version
$sScriptVersion = "0.2.2"
$banner=@"
_ _ ____ _ _
/ \ _____ _ _ __ ___ / \ ___ ___ ___ ___ ___| _ \ ___ _ __ _ __ ___ (_)___ ___(_) ___ _ __ ___
/ _ \ |_ / | | | '__/ _ \_____ / _ \ / __/ __/ _ \/ __/ __| |_) / _ \ '__| '_ ` _ \| / __/ __| |/ _ \| '_ \/ __|
/ ___ \ / /| |_| | | | __/_____/ ___ \ (_| (_| __/\__ \__ \ __/ __/ | | | | | | | \__ \__ \ | (_) | | | \__ \
/_/ \_\/___|\__,_|_| \___| /_/ \_\___\___\___||___/___/_| \___|_| |_| |_| |_|_|___/___/_|\___/|_| |_|___/
v$sScriptVersion by @0xcsandker
Here are the functions you might wanna use:
Invoke-AccessCheckForServicePrincipal ## Specific Service Principals
Invoke-AccessCheckForAllServicePrincipals ## All Service Principals
Invoke-AccessCheckForGroup ## Specific Group
Invoke-AccessCheckForAllGroups ## All Groups
Invoke-AccessCheckForUser ## Specifc User
Invoke-AccessCheckForAllUsers ## All Users
Invoke-AccessCheckForCurrentUser ## Your current User
Invoke-AllAccessChecks ## All of the above
Enumerate-AllHighPrivilegePrincipals ## Find all high privileged principals
Enumerate-MFAStatusOfHighPrivilegePrincipals ## Check the MFA Status of all high privileged principals
"@
$wellKnownApplicationIDs = @{
## NOTE: THIS is not a complete list, but rather an add-on-the-go-list
### I don't want this script to be too bloated
"00000002-0000-0ff1-ce00-000000000000" = "Exchange Online";
"00000003-0000-0ff1-ce00-000000000000" = "SharePoint Online";
"00000004-0000-0ff1-ce00-000000000000" = "Skype for Business online";
"0000000a-0000-0000-c000-000000000000" = "DeviceManagementApp (Microsoft Intune)";
"1b730954-1685-4b74-9bfd-dac224a7b894" = "MS Graph API";
"a0c73c16-a7e3-4564-9a95-2bdf47383716" = "MS Exchange Remote PowerShell";
"1fec8e78-bce4-4aaf-ab1b-5451cc387264" = "MS Teams";
"d3590ed6-52b3-4102-aeff-aad2292ab01c" = "Microsoft Support and Recovery Assistant (SARA)";
"ab9b8c07-8f02-4f72-87fa-80105867a763" = "OneDrive Sync Engine";
"de0853a1-ab20-47bd-990b-71ad5077ac7b" = "Windows Configuration Designer (WCD)";
"d4ebce55-015a-49b5-a083-c84d1797ae8c" = "Microsoft Intune Enrollment"
}
#-----------------------------------------------------------[Functions]------------------------------------------------------------
$MESSAGE_SUCCESS = '0'
$MESSAGE_FAIL = '1'
$MESSAGE_WARNING = '2'
$MESSAGE_INFO = '3'
Function __AAP-Log {
PARAM(
[String]
$Msg = '',
[String]
$MsgType = '',
[Int]
$IndentationLevel = 0,
[Switch]
$NoNewLine = $false
)
Process {
$initalFC = $host.UI.RawUI.ForegroundColor
switch ( $MsgType )
{
$MESSAGE_SUCCESS {
$host.UI.RawUI.ForegroundColor = "Green"
Write-Host "$(' '*$IndentationLevel)$($Msg)" -NoNewline:$NoNewLine
$host.UI.RawUI.ForegroundColor = $initalFC
break
}
$MESSAGE_FAIL {
$host.UI.RawUI.ForegroundColor = "Red"
Write-Host "$(' '*$IndentationLevel)$($Msg)" -NoNewline:$NoNewLine
$host.UI.RawUI.ForegroundColor = $initalFC
break
}
$MESSAGE_WARNING {
$host.UI.RawUI.ForegroundColor = "Yellow"
Write-Host "$(' '*$IndentationLevel)$($Msg)" -NoNewline:$NoNewLine
$host.UI.RawUI.ForegroundColor = $initalFC
break
}
$MESSAGE_INFO {
$host.UI.RawUI.ForegroundColor = "Cyan"
Write-Host "$(' '*$IndentationLevel)$($Msg)" -NoNewline:$NoNewLine
$host.UI.RawUI.ForegroundColor = $initalFC
break
}
default {
$host.UI.RawUI.ForegroundColor = "DarkGray"
Write-Host "$(' '*$IndentationLevel)$($Msg)" -NoNewline:$NoNewLine
$host.UI.RawUI.ForegroundColor = $initalFC
break
}
}
if( $Outfile ){
$script:gOutFileMessageBuffer += $Msg
If(-Not $NoNewLine) {
"$(' '*$IndentationLevel)$($script:gOutFileMessageBuffer)" | Out-File -Append -FilePath $Outfile
$script:gOutFileMessageBuffer = ""
}
}
}
}
Function __APP-DateTimeToString {
PARAM(
[Parameter()]
[DateTime]
$DateTime
)
Process {
If( $DateTime.getType() -eq [DateTime] ){
return $DateTime.GetDateTimeFormats('D')[-1]
}Else {
return $DateTime
}
}
}
Function __AAP-AppRoleIsHighPrivilegeConfidenceGuess {
PARAM(
[Object]
$AppRoleObject
)
Process {
##
## confidence level
## 0 => Assumed Not high privilege
## >0 => Assumed high privilege
## 100 => Certainly high privilege
$confidenceLevel = 0
If( $AppRoleObject.Value ){
If( $AppRoleObject.Value -eq 'Directory.ReadWrite.All' ){
$confidenceLevel = 100
}
ElseIf( $AppRoleObject.Value -Like '*FullControl.All' ){
$confidenceLevel = 10
}
ElseIf( $AppRoleObject.Value -Like '*ReadWrite.All' ){
$confidenceLevel = 10
}
ElseIf( $AppRoleObject.Value -Like 'full_access*' ){
$confidenceLevel = 10
}
}
## Return condifence level
return $confidenceLevel
}
}
Function __AAP-DisplayAppRoleAssignments {
PARAM(
[Object[]]
$AppRoleAssignments,
[Int]
$IndentationLevel = 0
)
Process {
ForEach($appRoleAssignment in $AppRoleAssignments){
$appRoleValue = 'default'
$appRole = $null
$highPrivConfidenceLevel = $null
If( $appRoleAssignment.AppRoleId -ne '00000000-0000-0000-0000-000000000000' ){
$appRole = ((Get-MgServicePrincipal -ServicePrincipalId $appRoleAssignment.ResourceId).AppRoles | ? {$_.Id -eq $appRoleAssignment.AppRoleId} | Select-Object -First 1)
$appRoleValue = $appRole.Value
If( $appRole ){
$highPrivConfidenceLevel =__AAP-AppRoleIsHighPrivilegeConfidenceGuess -AppRoleObject $appRole
}
}
__AAP-Log " Resource: $($appRoleAssignment.ResourceDisplayName) ($($appRoleAssignment.ResourceId))" -MsgType $MESSAGE_INFO -IndentationLevel $RecursionCounterDoNotUse
__AAP-Log " AppRole ID: $($appRoleAssignment.AppRoleId)" -MsgType $MESSAGE_INFO -IndentationLevel $RecursionCounterDoNotUse
If( $highPrivConfidenceLevel ){
__AAP-Log " AppRole ([!] Might be high privileged. Confidence $($highPrivConfidenceLevel)/100): " -MsgType $MESSAGE_WARNING -IndentationLevel $RecursionCounterDoNotUse
} Else {
__AAP-Log " AppRole:" -MsgType $MESSAGE_INFO -IndentationLevel $RecursionCounterDoNotUse
}
__AAP-Log " Value: $($appRoleValue)" -MsgType $MESSAGE_INFO -IndentationLevel $RecursionCounterDoNotUse
__AAP-Log " Display Name: $($appRole.DisplayName)" -MsgType $MESSAGE_INFO -IndentationLevel $RecursionCounterDoNotUse
__AAP-Log " AllowedMemberTypes: $($appRole.AllowedMemberTypes)" -MsgType $MESSAGE_INFO -IndentationLevel $RecursionCounterDoNotUse
__AAP-Log " Enabled: $($appRole.IsEnabled)" -MsgType $MESSAGE_INFO -IndentationLevel $RecursionCounterDoNotUse
__AAP-Log ""
#__AAP-Log " $($appRoleAssignmend.PrincipalType): $($appRoleAssignmend.PrincipalDisplayName) ($($appRoleAssignmend.PrincipalId))"
}
}
}
Function __AAP-DisplayOauth2PermissionGrants {
PARAM(
[Object[]]$Oauth2PermissionGrants
)
Process {
ForEach($Oauth2PermissionGrant in $Oauth2PermissionGrants){
$principal = If($Oauth2PermissionGrant.PrincipalId) {(Get-MgDirectoryObjectById -Ids $Oauth2PermissionGrant.PrincipalId).AdditionalProperties.userPrincipalName} Else { "" }
$resource = If($Oauth2PermissionGrant.ResourceId) {(Get-MgDirectoryObjectById -Ids $Oauth2PermissionGrant.ResourceId).AdditionalProperties.displayName} Else {""}
$client = If($Oauth2PermissionGrant.ClientId) {(Get-MgDirectoryObjectById -Ids $Oauth2PermissionGrant.ClientId).AdditionalProperties.displayName} Else {""}
__AAP-Log " Resource: $($resource) ($($Oauth2PermissionGrant.ResourceId))" -MsgType $MESSAGE_INFO
__AAP-Log " Consent To: $($Oauth2PermissionGrant.ConsentType)" -MsgType $MESSAGE_INFO
__AAP-Log " Principal: $($principal) ($($Oauth2PermissionGrant.PrincipalId))" -MsgType $MESSAGE_INFO
__AAP-Log " Scope: $($Oauth2PermissionGrant.Scope)" -MsgType $MESSAGE_INFO
__AAP-Log " Client: $($client) ($($Oauth2PermissionGrant.ClientId))" -MsgType $MESSAGE_INFO
__AAP-Log " Additional Attributes:" -MsgType $MESSAGE_INFO
$Oauth2PermissionGrant.AdditionalProperties.Keys.ForEach{" $($_): $($Oauth2PermissionGrant.AdditionalProperties[$_])"}
__AAP-Log ""
}
}
}
Function __AAP-GetHighPrivilegedDirectoryRoleTemplateMap {
PARAM()
Process {
return @{
'62E90394-69F5-4237-9190-012177145E10' = 'Global administrator';
'9B895D92-2CD3-44C7-9D02-A6AC2D5EA5C3' = 'Application administrator';
'C4E39BD9-1100-46D3-8C65-FB160DA0071F' = 'Authentication Administrator';
'B0F54661-2D74-4C50-AFA3-1EC803F12EFE' = 'Billing administrator';
'158C047A-C907-4556-B7EF-446551A6B5F7' = 'Cloud application administrator';
'B1BE1C3E-B65D-4F19-8427-F6FA0D97FEB9' = 'Conditional Access administrator';
'29232CDF-9323-42FD-ADE2-1D097AF3E4DE' = 'Exchange administrator';
'729827E3-9C14-49F7-BB1B-9608F156BBB8' = 'Helpdesk administrator';
'966707D0-3269-4727-9BE2-8C3A10F19B9D' = 'Password administrator';
'7BE44C8A-ADAF-4E2A-84D6-AB2649E08A13' = 'Privileged authentication administrator';
'E8611AB8-C189-46E8-94E1-60213AB1F814' = 'Privileged Role Administrator';
'194AE4CB-B126-40B2-BD5B-6091B380977D' = 'Security administrator';
'F28A1F50-F6E7-4571-818B-6A12F2AF6B6C' = 'SharePoint administrator';
'FE930BE7-5E62-47DB-91AF-98C3A49A38B1' = 'User administrator';
'3A2C62DB-5318-420D-8D74-23AFFEE5D9D5' = 'Intune Administrator';
'9F06204D-73C1-4D4C-880A-6EDB90606FD8' = 'Azure AD Joined Device Local Administrator';
## 'F2EF992C-3AFB-46B9-B7CF-A126EE74C451' = 'Global Reader';
}
}
}
Function __AAP-DisplayDirectoryRoleAssignment {
PARAM(
[Object]$MgDirectoryRole
)
Begin {
#$mgAllDirectoryRoles = Get-MgDirectoryRole -All
$highPrivilegedDirectoryRoles = __AAP-GetHighPrivilegedDirectoryRoleTemplateMap
}
Process {
## Azure AD Builtin Roles are described here: https://learn.microsoft.com/en-us/azure/active-directory/roles/permissions-reference
If( $MgDirectoryRole.RoleTemplateId.toUpper() -In $highPrivilegedDirectoryRoles.Keys ){
__AAP-Log " DirectoryRole: $($MgDirectoryRole.DisplayName) ([!] High privileged)" -MsgType $MESSAGE_WARNING
__AAP-Log " $($MgDirectoryRole.Description)"
}
Else {
__AAP-Log " DirectoryRole: $($MgDirectoryRole.DisplayName) (RoleTemplate ID: $($MgDirectoryRole.RoleTemplateId))" -MsgType $MESSAGE_INFO
__AAP-Log " $($MgDirectoryRole.Description)"
}
}
}
Function __AAP-DisplayHighPrivilegePrincipalMap {
PARAM()
Process {
__AAP-Log "## High Privileged Principals "
__AAP-Log "[*] Number of high privileged Accounts: $($script:gHighPrivilegdPrincipalMap.Keys.Count)" -MsgType $MESSAGE_WARNING
ForEach($principalID in $script:gHighPrivilegdPrincipalMap.Keys){
$principalEntries = $script:gHighPrivilegdPrincipalMap[$principalID]
$firstEntry = $principalEntries[0]
$absoluteConfidenceEntries = $principalEntries | ? { $_['ConfidenceLevel'] -eq 100 }
__AAP-Log "[+] $($firstEntry['principalName']) ($($firstEntry['principalID'])) [Type: $($firstEntry['principalType'])]" -MsgType $MESSAGE_SUCCESS
## If there is an entry with 100 confidence display only these entries
If( $absoluteConfidenceEntries ){
ForEach($absoluteConfidenceEntry in $absoluteConfidenceEntries){
__AAP-Log " Reason: $($absoluteConfidenceEntry['Reason']) (Confidence: $($absoluteConfidenceEntry['ConfidenceLevel'])/100)" -MsgType $MESSAGE_INFO
}
}
## Otherwise display all entries
Else {
ForEach($principalEntry in $principalEntries){
__AAP-Log " Reason: $($principalEntry['Reason']) (Confidence: $($principalEntry['ConfidenceLevel'])/100)" -MsgType $MESSAGE_INFO
}
}
}
}
}
Function __AAP-ResolveDirectoryObjectByID {
PARAM(
[String]
$ObjectID
)
Process {
$returnValue = "$($ObjectID)"
$directoryObject = Get-MgDirectoryObjectById -Ids $ObjectID -ErrorAction SilentlyContinue
If($directoryObject){
$aadDirectoryObjType = $directoryObject.AdditionalProperties['@odata.type']
Switch($aadDirectoryObjType){
'#microsoft.graph.user' {
$returnValue = "$($directoryObject.AdditionalProperties['userPrincipalName']) (User) [ID: $($ObjectID)]"
Break
}
'#microsoft.graph.group' {
$returnValue = "$($directoryObject.AdditionalProperties['displayName']) (Group) [ID: $($ObjectID)]"
Break
}
'#microsoft.graph.servicePrincipal' {
$returnValue = "$($directoryObject.AdditionalProperties['appDisplayName']) (ServicePrincipal) [ID: $($ObjectID)]"
Break
}
}
}
Else {
## Check if well known Application
If( $wellKnownApplicationIDs.Keys -Contains $ObjectID ){
$returnValue = "$($wellKnownApplicationIDs[$ObjectID]) (Application) [ID: $($ObjectID)]"
}
}
return $returnValue
}
}
Function __AAP-DisplayApplicableMFAConditionalAccessPolicyForUserID {
PARAM(
[Parameter()]
[String]
$UserID,
[Int]
$IndentationLevel = 0
)
Begin {
If( -Not $script:gActiveMFAConditionalAccessPolicies ){
$script:gActiveMFAConditionalAccessPolicies = Get-MgIdentityConditionalAccessPolicy -All | ?{ $_.State -ne "disabled" -And $_.GrantControls.BuiltInControls -Contains "mfa" }
}
}
Process {
$usersGroups = Get-MgUserMemberOf -UserId $UserID -All
$applicablePoliciesCount = 0
ForEach($conditionalAccessPolicy in $script:gActiveMFAConditionalAccessPolicies){
$policyApplies = $false
## Check Excludes
### Excluded by Group
If($conditionalAccessPolicy.Conditions.users.ExcludeGroups | ?{ $usersGroups.Id -Contains "$_" } ){
## Write-Verbose "[*] Group Policy exlcuded by group membership: $($conditionalAccessPolicy.DisplayName)"
Continue
}
### Excluded by User
If($conditionalAccessPolicy.Conditions.users.ExcludeUsers -Contains $UserID ) {
## Write-Verbose "[*] Group Policy exlcuded by group user: $($conditionalAccessPolicy.DisplayName)"
Continue
}
### Excluded by Role
If($conditionalAccessPolicy.Conditions.users.ExcludeRoles) {
$excludedRoles = $conditionalAccessPolicy.Conditions.Users.ExcludeRoles
ForEach($excludedRole in $excludedRoles){
If( ( Get-MgRoleManagementDirectoryRoleAssignment -Filter "(RoleDefinitionId eq '$($excludedRole)') and (PrincipalId eq '$($UserID)')") ){
#Write-Verbose "[*] Group Policy exlcuded by group role: $($conditionalAccessPolicy.DisplayName)"
Continue
}
}
}
## Check Includes
### Inclue by Group
If($conditionalAccessPolicy.Conditions.users.IncludeGroups | ?{ $usersGroups.Id -Contains "$_" } ){
#Write-Verbose "[+] Group Policy applies by Group: $($conditionalAccessPolicy.DisplayName)" -ForegroundColor DarkGreen
$policyApplies = $true
}
### Excluse by User
If(
( $conditionalAccessPolicy.Conditions.users.IncludeUsers -Contains "All") -Or
( $conditionalAccessPolicy.Conditions.users.IncludeUsers -Contains $UserID )
){
#Write-Verbose "[+] Group Policy applies by User: $($conditionalAccessPolicy.DisplayName)" -ForegroundColor DarkGreen
$policyApplies = $true
}
### Excluse by Role
If($conditionalAccessPolicy.Conditions.users.IncludeRoles) {
$includeRoles = $conditionalAccessPolicy.Conditions.Users.IncludeRoles
ForEach($includeRole in $includeRoles){
If( ( Get-MgRoleManagementDirectoryRoleAssignment -Filter "(RoleDefinitionId eq '$($includeRole)') and (PrincipalId eq '$($UserID)')") ){
#Write-Verbose "[+] Group Policy applies by group role: $($conditionalAccessPolicy.DisplayName)" -ForegroundColor DarkGreen
$policyApplies = $true
}
}
}
If($policyApplies){
$applicablePoliciesCount += 1
__AAP-Log "[+] $($conditionalAccessPolicy.DisplayName)" -MsgType $MESSAGE_SUCCESS -IndentationLevel $IndentationLevel
## Grant Controls
If( $conditionalAccessPolicy.GrantControls.BuiltInControls -eq "block" ){
## It should not be possible to set controls to "block" AND "mfa"
### Therefore this is just a saftey net
__AAP-Log "==> Block access" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
} ElseIf ($conditionalAccessPolicy.GrantControls.BuiltInControls.Count) {
__AAP-Log "==> Grant access " -NoNewline -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
If( $conditionalAccessPolicy.GrantControls.BuiltInControls.Count ){
__AAP-Log "IF [ " -NoNewline -MsgType $MESSAGE_INFO
ForEach($bultInControl in $conditionalAccessPolicy.GrantControls.BuiltInControls){
If( ($conditionalAccessPolicy.GrantControls.BuiltInControls.IndexOf($bultInControl) % 2) -ne 0 ){
__AAP-Log "$($conditionalAccessPolicy.GrantControls.Operator) " -NoNewline -MsgType $MESSAGE_INFO
}
__AAP-Log "$($bultInControl) " -NoNewline -MsgType $MESSAGE_INFO
}
__AAP-Log "]" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
} Else {
__AAP-Log "" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel ## newline
}
}
## Session Controls
If( $conditionalAccessPolicy.SessionControls.ApplicationEnforcedRestrictions.IsEnabled ){
__AAP-Log "--> Session Control: Use app enforced restrictions" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.SessionControls.CloudAppSecurity.IsEnabled ){
__AAP-Log "--> Session Control: CloudAppSecurity (Type: $($conditionalAccessPolicy.SessionControls.CloudAppSecurity.CloudAppSecurityType))" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.SessionControls.ContinuousAccessEvaluation.Mode ){
__AAP-Log "--> Session Control: Customize continuous access evaluation (Mode: $($conditionalAccessPolicy.SessionControls.ContinuousAccessEvaluation.Mode))" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.SessionControls.DisableResilienceDefaults ){
__AAP-Log "--> Session Control: Disable resilience defaults" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.SessionControls.PersistentBrowser.IsEnabled ){
__AAP-Log "--> Session Control: Persistent browser session" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.SessionControls.SignInFrequency.IsEnabled ){
__AAP-Log "--> Session Control: Sign-in frequency" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
__AAP-Log " $($conditionalAccessPolicy.SessionControls.SignInFrequency.Value) $($conditionalAccessPolicy.SessionControls.SignInFrequency.Type) ($($conditionalAccessPolicy.SessionControls.SignInFrequency.FrequencyInterval))" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
## Applications
ForEach($excludedApplication in $conditionalAccessPolicy.Conditions.Applications.ExcludeApplications){
## Values could be "All", "<AppName>", "<ID>"
$excludedApp = __AAP-ResolveDirectoryObjectByID $excludedApplication
__AAP-Log " Excluded Application: $($excludedApp)" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
ForEach($includedApplication in $conditionalAccessPolicy.Conditions.Applications.IncludeApplications){
## Values could be "All", "<AppName>", "<ID>"
$includeApp = __AAP-ResolveDirectoryObjectByID $includedApplication
__AAP-Log " Included Application: $($includeApp)" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.Conditions.Applications.IncludeAuthenticationContextClassReferences ){
__AAP-Log "TODO IncludeAuthenticationContextClassReferences: $($conditionalAccessPolicy.Conditions.Applications.IncludeAuthenticationContextClassReferences )" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.Conditions.Applications.IncludeUserActions ){
__AAP-Log "TODO IncludeUserActions: $($conditionalAccessPolicy.Conditions.Applications.IncludeUserActions )" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.Conditions.Applications.AdditionalProperties.Count ){
__AAP-Log "TODO AdditionalProperties: $($conditionalAccessPolicy.Conditions.Applications.AdditionalProperties | fl )" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
## ClientApps
__AAP-Log " Client Apps: " -NoNewline -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
ForEach($clientApp in $conditionalAccessPolicy.Conditions.ClientAppTypes){
If( ($conditionalAccessPolicy.Conditions.ClientAppTypes.IndexOf($clientApp) % 2) -ne 0 ){
__AAP-Log ", " -NoNewline -MsgType $MESSAGE_INFO
}
__AAP-Log "$($clientApp)" -NoNewline -MsgType $MESSAGE_INFO
}
__AAP-Log "" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel ## new line
## Devices
If( $conditionalAccessPolicy.Conditions.Devices.ExcludeDeviceStates ){
__AAP-Log " Excluded Device States: $($conditionalAccessPolicy.Conditions.Devices.ExcludeDeviceState)" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.Conditions.Devices.ExcludeDevices ){
__AAP-Log " Excluded Devices: $($conditionalAccessPolicy.Conditions.Devices.ExcludeDevices)" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.Conditions.Devices.IncludeDeviceStates ){
__AAP-Log " Included Device States: $($conditionalAccessPolicy.Conditions.Devices.IncludeDeviceStates)" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.Conditions.Devices.IncludeDevices ){
__AAP-Log " Included Devices: $($conditionalAccessPolicy.Conditions.Devices.IncludeDevices)" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
## Locations
If( $conditionalAccessPolicy.Conditions.Locations.ExcludeLocations ){
__AAP-Log " Excluded Locations: $($conditionalAccessPolicy.Conditions.Locations.ExcludeLocations)" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.Conditions.Locations.IncludeLocations ){
__AAP-Log " Included Locations: $($conditionalAccessPolicy.Conditions.Locations.IncludeLocations)" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
## Plattforms
If( $conditionalAccessPolicy.Conditions.Platforms.ExcludePlatforms ){
__AAP-Log " Excluded Plattforms: $($conditionalAccessPolicy.Conditions.Platforms.ExcludeLocations)" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
If( $conditionalAccessPolicy.Conditions.Platforms.IncludePlatforms ){
__AAP-Log " Included Plattforms: $($conditionalAccessPolicy.Conditions.Platforms.IncludePlatforms)" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
## ServicePrincipalRiskLevels
If( $conditionalAccessPolicy.Conditions.ServicePrincipalRiskLevels.Count ){
__AAP-Log " TODO: ServicePrincipalRiskLevels" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
## SignInRiskLevels
If( $conditionalAccessPolicy.Conditions.SignInRiskLevels.Count ){
__AAP-Log " TODO: SignInRiskLevels" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
## UserRiskLevels
If( $conditionalAccessPolicy.Conditions.UserRiskLevels.Count ){
__AAP-Log " TODO: UserRiskLevels" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
}
#Write-Host "[+] Group Policy applies ??? last call : $($conditionalAccessPolicy.DisplayName)" -ForegroundColor DarkGreen
}
If( $applicablePoliciesCount -eq 0 ){
## No policy applies
__AAP-Log " -- No MFA Conditional Access Policy applies for this user --" -MsgType $MESSAGE_INFO -IndentationLevel $IndentationLevel
}
}
}
Function __AAP-CheckRequiredModules {
PARAM()
Process {
$modulesInstalled = $true
## Microsoft.Graph
if ( -Not (Get-Module -ListAvailable -Name Microsoft.Graph) ){
__AAP-Log -Msg "[-] Module 'Microsoft.Graph' does not exist." -MsgType $MESSAGE_FAIL
__AAP-Log -Msg " Install it via: Install-Module Microsoft.Graph" -MsgType $MESSAGE_WARNING
$modulesInstalled = $false
}
## AADInternals
if ( -Not (Get-Module -ListAvailable -Name AADInternals) ) {
__AAP-Log -Msg "[-] Module 'AADInternals' does not exist." -MsgType $MESSAGE_FAIL
__AAP-Log -Msg " Install it via: Install-Module AADInternals" -MsgType $MESSAGE_WARNING
$modulesInstalled = $false
}
## AzureADPreview
if ( -Not (Get-Module -ListAvailable -Name AzureADPreview) ) {
__AAP-Log -Msg "[-] Module 'AzureADPreview' does not exist." -MsgType $MESSAGE_FAIL
__AAP-Log -Msg " Install it via: Install-Module AzureADPreview" -MsgType $MESSAGE_WARNING
$modulesInstalled = $false
}
return $modulesInstalled
}
}
Function __AAP-ImportRequiredModules {
PARAM()
Process {
Try {
Import-Module AADInternals 6>$null | Out-Null
Import-Module Microsoft.Graph.Applications | Out-Null
Import-Module AzureADPreview | Out-Null
return $true
}
Catch {
__AAP-Log -Msg "[-] An error occured while trying to import required modules." -MsgType $MESSAGE_FAIL
__AAP-Log -Msg " The error was: $_"
return $false
}
}
}
Function __AAP-GetAcessTokenForAADGraphWithRefreshToken {
PARAM(
[Parameter()]
[String]
$RefreshToken = $global:__AAPgRefreshToken,
[Parameter()]
[String]
$Tenant = $global:__AAPgTenantID
)
Process {
return (Get-AADIntAccessTokenWithRefreshToken -Resource "https://graph.windows.net" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -RefreshToken $RefreshToken -Tenant $global:__AAPgTenantID)
}
}
Function __AAP-GetAcessTokenForMSGraphWithRefreshToken {
PARAM(
[Parameter()]
[String]
$RefreshToken = $global:__AAPgRefreshToken,
[Parameter()]
[String]
$Tenant = $global:__AAPgTenantID
)
Process {
return (Get-AADIntAccessTokenWithRefreshToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -RefreshToken $RefreshToken -Tenant $global:__AAPgTenantID)
}
}
Function __AAP-GetAcessTokenForMSGraphWithCredentials {
PARAM(
[Parameter()]
[String]
$Tenant = $global:__AAPgTenantID
)
Process {
$accessTokenMSGraph, $refreshToken = Get-AADIntAccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -IncludeRefreshToken:$true -Tenant $Tenant
return @($accessTokenMSGraph, $refreshToken)
}
}
Function __AAP-ConnectMicrosoftGraph {
PARAM(
[Parameter()]
[String]
$Tenant
)
Begin {
## Tenant dependent Script global variables
$script:gAllMgDirectoryRoles = @()
$script:gHighPrivilegdPrincipalMap = @{}
$script:gLastCollectionOfHighPrivilegdPrincipalMap = $null
}
Process{
$global:__AAPgAccessTokenMSGraph, $global:__AAPgRefreshToken = __AAP-GetAcessTokenForMSGraphWithCredentials -Tenant $Tenant
If( $global:__AAPgAccessTokenMSGraph ){
Connect-MgGraph -AccessToken $global:__AAPgAccessTokenMSGraph
Select-MgProfile -Name "beta"
$global:__AAPgTenantID = (Get-MgContext).TenantId
}
Else {
__AAP-Log -Msg "[-] An error occured while trying to connect to Micrsoft Graph." -MsgType $MESSAGE_FAIL
__AAP-Log -Msg " We can't continue. Please retry..."
Break
}
return $accessTokenMSGraph
}
}
Function __AAP-ConnectAllResources {
PARAM(
[Parameter()]
[String]
$Tenant
)
Process {
__AAP-Log "[*] Connecting to Microsoft Graph..."
$accessTokenMSGraph = __AAP-ConnectMicrosoftGraph -Tenant $Tenant
__AAP-Log "[*] Connecting to AzureAD Graph..."
$graphContext = Get-MgContext
Connect-AzureAD -AccountId $graphContext.Account | Out-Null
}
}
Function __AAP-ConnectIfNecessary {
PARAM(
[Parameter()]
[String]
$Tenant
)
Process {
## Check if given Tenant matches
If( $Tenant -And ( $global:__AAPgTenantID -ne (Get-AADIntTenantID -Domain $Tenant) ) ){
__AAP-Log "[*] Connecting Microsoft Graph to different Tenant..."
__AAP-ConnectAllResources -Tenant $Tenant
}
## Check if connected
If( -Not (Get-MgContext) ){
__AAP-ConnectAllResources -Tenant $Tenant
}
## Test connection
Try {
$mgUser = Get-MgUser -Top 1 -ErrorAction Stop
} Catch {
$caughtError = $_
If( $caughtError.ToString() -Like "*Authentication needed*" ){
__AAP-Log -Msg "[*] We need to re-authenticate..." -MsgType $MESSAGE_WARNING
__AAP-ConnectAllResources -Tenant $Tenant
}
If( $caughtError.ToString() -Like "*token has expired*" ){
__AAP-Log -Msg "[*] Access Token expired we need to re-authenticate..." -MsgType $MESSAGE_WARNING
__AAP-ConnectAllResources -Tenant $Tenant
}
}
}
}
Function __AAP-AddToHighPrivilegePrincipalMap {
PARAM(
[Parameter(Mandatory)]
[String]
$PrincipalID,
[String]
$PrincipalName,
[String]
$Reason,
[Parameter(Mandatory)]
[ValidateSet("User","Group","ServicePrincipal","Unknown", IgnoreCase = $true)]
[String]
$PrincipalType,
[Int]
$ConfidenceLevel = -1
)
Process {
$entryArray = If( $script:gHighPrivilegdPrincipalMap.Keys -Contains $PrincipalID ){ ,$script:gHighPrivilegdPrincipalMap.Item($PrincipalID) } Else { ,@() }
## Update Entries with a reason already added
$updateEntries = $entryArray | ? { $_['Reason'] -eq $Reason }
If( $updateEntries ){
ForEach($updateEntry in $updateEntries){
## Update only if the confidence level increased
If( $ConfidenceLevel -gt $updateEntry['ConfidenceLevel'] ){
$updateEntry['ConfidenceLevel'] = $ConfidenceLevel
}
}
}
## Add new entry if new reason
Else {
$entryArray += @{
'principalID' = $PrincipalID;
'principalName' = $PrincipalName;
'principalType' = $PrincipalType;
'ConfidenceLevel' = $ConfidenceLevel;
'Reason' = $Reason
}
$script:gHighPrivilegdPrincipalMap[$PrincipalID] = $entryArray
}
}
}
Function __AAP-DisplayNonHighPrivilegedRoleAssignments {
PARAM(
[Parameter()]
[hashtable]
$NonHighPrivilegedRoleAssignments
)
Process {
ForEach($roleTemplateName in $NonHighPrivilegedRoleAssignments.Keys){
__AAP-Log "[*] The Directory Role '$($roleTemplateName)' is currently not considered high privileged, but has the following members:" -MsgType $MESSAGE_WARNING
ForEach($principalDisplayStr in $NonHighPrivilegedRoleAssignments[$roleTemplateName]){
__AAP-Log " $($principalDisplayStr)"
}
}
}
}
Function __AAP-CheckIfMemberOfPrivilegedDirectoryRole {
PARAM(
[Parameter()]
[String]
$PrincipalID,
[Parameter()]
[hashtable]
$NonHighPrivilegedRoleAssignments,
[Parameter()]
[String]
$TemplateID,
[Parameter()]
[String]
$TemplateName = "",
[Parameter()]
[Switch]
$AssignedViaPIM = $false,
[Parameter()]
[Object]
$PIMAssignmentEndDateTime,
[Parameter()]
[String]
$PIMAssignmentState
)
Begin {
If( $TemplateName -eq "" ){
$mgDirectoryRoleTemplate = Get-MgDirectoryRoleTemplate -DirectoryRoleTemplateId $TemplateID
If( $mgDirectoryRoleTemplate ){
$TemplateName = $mgDirectoryRoleTemplate.DisplayName
}
}
}
Process {
### Check if role is high privileged
If( $templateID -In $highPrivilegedDirectoryRoleTemplatesMap.Keys ){
## 100 for Global Administrator, 99 for all others
$confidenceLevel = If( $templateID -eq '62E90394-69F5-4237-9190-012177145E10' ){ 100 } Else { 99 }
## Get corresponding principal
$principalObjectData = (Get-MgDirectoryObjectById -Ids $PrincipalID)
$principalID = $principalObjectData.Id
$principalName = $null
$principalType = 'Unknown'
$highPrivReason = "High privileged directory Role assigned: $($highPrivilegedDirectoryRoleTemplatesMap[$templateID])"
If( $AssignedViaPIM ){
If( $PIMAssignmentEndDateTime ){
$endDateStr = __APP-DateTimeToString -DateTime $PIMAssignmentEndDateTime
$highPrivReason = "High privileged directory Role assigned (via time-based PIM assignment, ending $($endDateStr)): $($highPrivilegedDirectoryRoleTemplatesMap[$templateID])"
If( $PIMAssignmentState ){
$highPrivReason = "High privileged directory Role assigned (via $($PIMAssignmentState) time-based PIM assignment, ending $($endDateStr)): $($highPrivilegedDirectoryRoleTemplatesMap[$templateID])"
}
}
Else {
$highPrivReason = "High privileged directory Role assigned (via permanent PIM assignment): $($highPrivilegedDirectoryRoleTemplatesMap[$templateID])"
If( $PIMAssignmentState ){
$highPrivReason = "High privileged directory Role assigned (via $($PIMAssignmentState) permanent PIM assignment): $($highPrivilegedDirectoryRoleTemplatesMap[$templateID])"
}
}
}
If( $principalObjectData.AdditionalProperties ){
## Resolve principal
$aadDirectoryObjType = $principalObjectData.AdditionalProperties['@odata.type']
Switch($aadDirectoryObjType){
'#microsoft.graph.user' {
$principalType = 'User'
$principalName = $principalObjectData.AdditionalProperties['userPrincipalName']
## Add entry
__AAP-AddToHighPrivilegePrincipalMap -PrincipalID $principalID -PrincipalName $principalName -Reason $highPrivReason -PrincipalType $principalType -ConfidenceLevel $confidenceLevel
Break
}
'#microsoft.graph.group' {
$principalType = 'Group'
## Resovle members
$securityIdentifier = $principalObjectData.AdditionalProperties['securityIdentifier']
$mgGroup = Get-MgGroup -Filter "securityIdentifier eq '$($securityIdentifier)'" -Top 1
If( $mgGroup ){
$mgGroupMembers = Get-MgGroupTransitiveMember -GroupId $mgGroup.Id
ForEach($mgGroupMember in $mgGroupMembers){
$principalID = $mgGroupMember.Id
$principalName = $null
$groupMemberObjType = $mgGroupMember.AdditionalProperties['@odata.type']
$highPrivReason = "Member of group ($($mgGroup.DisplayName)) with high privileged directory Role: $($highPrivilegedDirectoryRoleTemplatesMap[$templateID])"
If( $AssignedViaPIM ){
If( $PIMAssignmentEndDateTime ){
$endDateStr = __APP-DateTimeToString -DateTime $PIMAssignmentEndDateTime
$highPrivReason = "Member of group ($($mgGroup.DisplayName)) with high privileged directory Role (via time-based PIM assignment, ending $($endDateStr)): $($highPrivilegedDirectoryRoleTemplatesMap[$templateID])"
If( $PIMAssignmentState ){
$highPrivReason = "Member of group ($($mgGroup.DisplayName)) with high privileged directory Role (via $($PIMAssignmentState) time-based PIM assignment, ending $($endDateStr)): $($highPrivilegedDirectoryRoleTemplatesMap[$templateID])"
}
}Else {
$highPrivReason = "Member of group ($($mgGroup.DisplayName)) with high privileged directory Role (via permanent PIM assignment): $($highPrivilegedDirectoryRoleTemplatesMap[$templateID])"
If( $PIMAssignmentState ){
$highPrivReason = "Member of group ($($mgGroup.DisplayName)) with high privileged directory Role (via $($PIMAssignmentState) permanent PIM assignment): $($highPrivilegedDirectoryRoleTemplatesMap[$templateID])"
}
}
}
Switch($groupMemberObjType){
'#microsoft.graph.user' {
$principalType = 'User'
$principalName = $mgGroupMember.AdditionalProperties['userPrincipalName']
Break
}
'#microsoft.graph.servicePrincipal' {
$principalType = 'ServicePrincipal'
$principalName = $mgGroupMember.AdditionalProperties['appDisplayName']
Break
}
}
## Add entry
__AAP-AddToHighPrivilegePrincipalMap -PrincipalID $principalID -PrincipalName $principalName -Reason $highPrivReason -PrincipalType $principalType -ConfidenceLevel $confidenceLevel
}
}
Break
}
'#microsoft.graph.servicePrincipal' {
$principalType = 'ServicePrincipal'
$principalName = $principalObjectData.AdditionalProperties['appDisplayName']
## Add entry
__AAP-AddToHighPrivilegePrincipalMap -PrincipalID $principalID -PrincipalName $principalName -Reason $highPrivReason -PrincipalType $principalType -ConfidenceLevel $confidenceLevel
Break
}
}
}
}Else {
$principalEntries = If( $NonHighPrivilegedRoleAssignments.Keys -Contains $TemplateName ){ ,$NonHighPrivilegedRoleAssignments.Item($TemplateName) } Else { ,@() }
## Add Principal if not already contained
If( $principalEntries.Keys -NotContains $PrincipalID ){
$principalDisplayStr = __AAP-ResolveDirectoryObjectByID -ObjectID $PrincipalID
If( $AssignedViaPIM ){
If( $PIMAssignmentEndDateTime ){
$endDateStr = __APP-DateTimeToString -DateTime $PIMAssignmentEndDateTime
If( $PIMAssignmentState ){
$principalDisplayStr += " [[ Assigned via $($PIMAssignmentState) PIM assignment (ends '$($endDateStr)') ]]"
}Else {
$principalDisplayStr += " [[ Assigned via PIM assignment (ends '$($endDateStr)') ]]"
}
}
Else {
If( $PIMAssignmentState ){
$principalDisplayStr += " [[ Assigned via $($PIMAssignmentState) PIM assignment (permanent) ]]"
}Else {
$principalDisplayStr += " [[ Assigned via PIM assignment (permanent) ]]"
}
}
}
$principalEntries += @($principalDisplayStr)
}
$NonHighPrivilegedRoleAssignments[$TemplateName] = $principalEntries
}
}
}
#-----------------------------------------------------------[Execution]------------------------------------------------------------
Function Invoke-AccessCheckForServicePrincipal {
PARAM(
[Parameter(Mandatory, ParameterSetName="ServicePrincipalIdentifier")]
[Object]
$ServicePrincipalIdentifier,
[Parameter(Mandatory, ParameterSetName="MgServicePrincipalObject")]
[Object]
$MgServicePrincipalObject,
[Parameter()]
[String]
$Outfile = $false,
[Parameter()]
[String]
$Tenant
)
Begin {
__AAP-ConnectIfNecessary -Tenant $Tenant
If($MgServicePrincipalObject){
$mgServicePrincipal = $MgServicePrincipalObject
}
ElseIf($ServicePrincipalIdentifier) {
## Try to find service principals via ID
$mgServicePrincipal = Get-MgServicePrincipal -ServicePrincipalId $ServicePrincipalIdentifier -ErrorAction SilentlyContinue
If(-Not $mgServicePrincipal){
## Try to find service principal via appID
$mgServicePrincipal = Get-MgServicePrincipal -Filter "appId eq '$($ServicePrincipalIdentifier)'" -Top 1 -ErrorAction SilentlyContinue
}
If(-Not $mgServicePrincipal){
__AAP-Log "[-] Could not find service principal: $($ServicePrincipalIdentifier)" -MsgType $MESSAGE_FAIL
}
}
Else {
$mgServicePrincipal = $null
}
}
Process {
If( $mgServicePrincipal ){
$appRoleAssignmendToResult = Get-MgServicePrincipalAppRoleAssignedTo -All -ServicePrincipalId $mgServicePrincipal.Id
$appRoleAssignmentsResult = Get-MgServicePrincipalAppRoleAssignment -All -ServicePrincipalId $mgServicePrincipal.Id
$oauthPermissionsResult = Get-MgServicePrincipalOauth2PermissionGrant -All -ServicePrincipalId $mgServicePrincipal.Id
$owner = Get-MgServicePrincipalOwner -All -ServicePrincipalId $mgServicePrincipal.Id
$delegPermissionsClassifciation = Get-MgServicePrincipalDelegatedPermissionClassification -All -ServicePrincipalId $mgServicePrincipal.Id
$mgOwnedObjectsByServicePrincipal = Get-MgServicePrincipalOwnedObject -All -ServicePrincipalId $mgServicePrincipal.Id
$createdObjs = Get-MgServicePrincipalCreatedObject -All -ServicePrincipalId $mgServicePrincipal.Id
$resourceSpecificAppPermissions = $mgServicePrincipal.ResourceSpecificApplicationPermissions
#$oauthPermissionGrants = $mgServicePrincipal.Oauth2PermissionGrants
#$oauthPermissionScopes = $mgServicePrincipal.Oauth2PermissionScopes
__AAP-Log "### Service Principal: $($mgServicePrincipal.DisplayName) ($($mgServicePrincipal.Id))"
## Owned Objects
if( $mgOwnedObjectsByServicePrincipal.Length -gt 0 ){
ForEach($mgOwnedObjectRef in $mgOwnedObjectsByServicePrincipal){
__AAP-Log "[+] User owns the following object: $($mgOwnedObjectRef.Id)" -MsgType $MESSAGE_SUCCESS
$mgOwnedObjProperties = (Get-MgDirectoryObjectById -Ids $mgOwnedObjectRef.Id).AdditionalProperties
if( $mgOwnedObjProperties ){
$mgOwnedObjProperties.Keys | %{ __AAP-Log " $($_): $($mgOwnedObjProperties[$_])" -MsgType $MESSAGE_INFO }
}
}
}
## Application-Type API Permissions of the service principal
if( $appRoleAssignmentsResult ){
__AAP-Log "[+] Application-Type API Permission access rights of this service principal:" -MsgType $MESSAGE_SUCCESS
__AAP-DisplayAppRoleAssignments -AppRoleAssignments $appRoleAssignmentsResult
}
## Delegated-Type API Permissions of the service principal
if( $oauthPermissionsResult ){
__AAP-Log "[+] Delegated-Type API Permission access rights of this service principal:" -MsgType $MESSAGE_SUCCESS
__AAP-DisplayOauth2PermissionGrants -Oauth2PermissionGrants $oauthPermissionsResult
}
## Principals with assigned AppRoles to this service account
if( $appRoleAssignmendToResult ){
__AAP-Log "[+] The following principals have an AppRole assigned for this this service account:" -MsgType $MESSAGE_SUCCESS