-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathOAuthPermissions-Analyzer.ps1
More file actions
1531 lines (1307 loc) · 89.4 KB
/
OAuthPermissions-Analyzer.ps1
File metadata and controls
1531 lines (1307 loc) · 89.4 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
# OAuthPermissions-Analyzer
#
# @author: Martin Willing
# @copyright: Copyright (c) 2026 Martin Willing. All rights reserved. Licensed under the MIT license.
# @contact: Any feedback or suggestions are always welcome and much appreciated - mwilling@lethal-forensics.com
# @url: https://lethal-forensics.com/
# @date: 2026-05-01
#
#
# ██╗ ███████╗████████╗██╗ ██╗ █████╗ ██╗ ███████╗ ██████╗ ██████╗ ███████╗███╗ ██╗███████╗██╗ ██████╗███████╗
# ██║ ██╔════╝╚══██╔══╝██║ ██║██╔══██╗██║ ██╔════╝██╔═══██╗██╔══██╗██╔════╝████╗ ██║██╔════╝██║██╔════╝██╔════╝
# ██║ █████╗ ██║ ███████║███████║██║█████╗█████╗ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║███████╗██║██║ ███████╗
# ██║ ██╔══╝ ██║ ██╔══██║██╔══██║██║╚════╝██╔══╝ ██║ ██║██╔══██╗██╔══╝ ██║╚██╗██║╚════██║██║██║ ╚════██║
# ███████╗███████╗ ██║ ██║ ██║██║ ██║███████╗ ██║ ╚██████╔╝██║ ██║███████╗██║ ╚████║███████║██║╚██████╗███████║
# ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═════╝╚══════╝
#
#
# Dependencies:
#
# ImportExcel v7.8.10 (2024-10-21)
# https://github.com/dfinke/ImportExcel
#
#
# Tested on Windows 10 Pro (x64) Version 22H2 (10.0.19045.6456) and PowerShell 5.1 (5.1.19041.6456)
# Tested on Windows 10 Pro (x64) Version 22H2 (10.0.19045.6456) and PowerShell 7.6.1
#
#
#############################################################################################################################################################################################
#############################################################################################################################################################################################
<#
.SYNOPSIS
OAuthPermissions-Analyzer - Automated Processing of M365 OAuth Permissions for DFIR
.DESCRIPTION
OAuthPermissions-Analyzer.ps1 is a PowerShell script utilized to simplify the analysis of M365 OAuth Permissions extracted via "Microsoft Extractor Suite" by Invictus Incident Response.
https://github.com/invictus-ir/Microsoft-Extractor-Suite (Microsoft-Extractor-Suite v4.0.2)
https://microsoft-365-extractor-suite.readthedocs.io/en/latest/functionality/Azure/OAuthPermissions.html#id2
List delegated permissions (OAuth2PermissionGrants) and application permissions (AppRoleAssignments).
Note: Get-OAuthPermissionGraph (Microsoft Graph)
.PARAMETER OutputDir
Specifies the output directory. Default is "$env:USERPROFILE\Desktop\OAuthPermissions-Analyzer".
Note: The subdirectory 'OAuthPermissions-Analyzer' is automatically created.
.PARAMETER Path
Specifies the path to the CSV-based input file (*-OAuthPermissions.csv).
.EXAMPLE
PS> .\OAuthPermissions-Analyzer.ps1
.EXAMPLE
PS> .\OAuthPermissions-Analyzer.ps1 -Path "$env:USERPROFILE\Desktop\*-OAuthPermissions.csv"
.EXAMPLE
PS> .\OAuthPermissions-Analyzer.ps1 -Path "H:\Microsoft-Extractor-Suite\*-OAuthPermissions.csv" -OutputDir "H:\Microsoft-Analyzer-Suite"
.NOTES
Author - Martin Willing
.LINK
https://lethal-forensics.com/
#>
#############################################################################################################################################################################################
#############################################################################################################################################################################################
# Incident Response Checklist (Source: Invictus Incident Response)
# Use this checklist to remediate and recover from Azure App related incidents!
# - Identify the affected user accounts and applications: Determine which user accounts and applications were involved in the security incident.
# - Disable affected user accounts: Disable the user accounts associated with the security incident to prevent further unauthorized access.
# - Revoke application access: Revoke access to the affected applications for the disabled user accounts.
# - Review application permissions: Review the permissions granted to the affected applications and remove any unnecessary permissions.
# - Reset application credentials: Reset any credentials, such as passwords or secrets, for the affected applications.
# - Monitor for suspicious activity: Monitor the affected applications for any suspicious activity that could indicate ongoing security threats.
# - Investigate the security incident: Conduct a thorough investigation of the security incident to identify any vulnerabilities that need to be addressed to prevent similar incidents in the future.
# - Implement remediation measures: Implement remediation measures based on the findings of the investigation to address any security weaknesses and prevent future incidents.
# By following these steps, you can effectively revoke access for Azure applications after a security incident and take appropriate measures to protect your organization's data and resources.
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region CmdletBinding
[CmdletBinding()]
Param(
[String]$Path,
[String]$OutputDir
)
#endregion CmdletBinding
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region Declarations
# Declarations
# Script Root
if ($PSVersionTable.PSVersion.Major -gt 2)
{
# PowerShell 3+
$SCRIPT_DIR = $PSScriptRoot
}
else
{
# PowerShell 2
$SCRIPT_DIR = Split-Path -Parent $MyInvocation.MyCommand.Definition
}
# Colors
Add-Type -AssemblyName System.Drawing
$script:HighColor = [System.Drawing.Color]::FromArgb(255,0,0) # Red
$script:MediumColor = [System.Drawing.Color]::FromArgb(255,192,0) # Orange
$script:LowColor = [System.Drawing.Color]::FromArgb(255,255,0) # Yellow
$script:Green = [System.Drawing.Color]::FromArgb(0,176,80) # Green
# Output Directory
if (!($OutputDir))
{
$script:OUTPUT_FOLDER = "$env:USERPROFILE\Desktop\OAuthPermissions-Analyzer" # Default
}
else
{
if ($OutputDir -cnotmatch '.+(?=\\)')
{
Write-Host "[Error] You must provide a valid directory path." -ForegroundColor Red
Exit
}
else
{
$script:OUTPUT_FOLDER = "$OutputDir\OAuthPermissions-Analyzer" # Custom
}
}
# Configuration File (JSON)
if(!(Test-Path "$PSScriptRoot\Config.json"))
{
Write-Host "[Error] Config.json NOT found." -ForegroundColor Red
Exit
}
else
{
$Config = Get-Content "$PSScriptRoot\Config.json" | ConvertFrom-Json
# IPinfo CLI - Access Token
$script:Token = $Config.IPinfo.AccessToken
# BackgroundColor
if ($Config.ImportExcel.BackgroundColor)
{
if ($Config.ImportExcel.BackgroundColor -cnotmatch '^(([0-1]?[0-9]?[0-9])|([2][0-4][0-9])|(25[0-5])),(([0-1]?[0-9]?[0-9])|([2][0-4][0-9])|(25[0-5])),(([0-1]?[0-9]?[0-9])|([2][0-4][0-9])|(25[0-5]))$') # <0-255>,<0-255>,<0-255>
{
Write-Host "[Error] You must provide a valid RGB Color Code." -ForegroundColor Red
Return
}
}
# Excel - Color Scheme
$script:BackgroundColor = [System.Drawing.Color]$Config.ImportExcel.BackgroundColor
$script:FontColor = $Config.ImportExcel.FontColor
}
#endregion Declarations
#############################################################################################################################################################################################
#region Header
# Check if the PowerShell script is being run with admin rights
if (!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
Write-Host "[Error] This PowerShell script must be run with admin rights." -ForegroundColor Red
Exit
}
# Check if PowerShell module 'ImportExcel' is installed
if (!(Get-Module -ListAvailable -Name ImportExcel))
{
Write-Host "[Error] Please install 'ImportExcel' PowerShell module." -ForegroundColor Red
Write-Host "[Info] Check out: https://github.com/evild3ad/Microsoft-Analyzer-Suite/wiki#setup"
Exit
}
# Windows Title
$DefaultWindowsTitle = $Host.UI.RawUI.WindowTitle
$Host.UI.RawUI.WindowTitle = "OAuthPermissions-Analyzer - Automated Processing of M365 OAuth Permissions for DFIR"
# Check if Microsoft Excel is running and stop all instances
$ProcessName = "EXCEL"
$Process = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue
if($Process)
{
Stop-Process -Id $Process.Id -Force
Start-Sleep -Milliseconds 500
}
# Flush Output Directory
if (Test-Path "$OUTPUT_FOLDER")
{
Get-ChildItem -Path "$OUTPUT_FOLDER" -Force -Recurse -ErrorAction SilentlyContinue | Remove-Item -Force -Recurse
New-Item "$OUTPUT_FOLDER" -ItemType Directory -Force | Out-Null
}
else
{
New-Item "$OUTPUT_FOLDER" -ItemType Directory -Force | Out-Null
}
# Add the required MessageBox class (Windows PowerShell)
Add-Type -AssemblyName System.Windows.Forms
# Function Get-ScopeLink by Merill Fernando (@merill)
Function Get-ScopeLink($Scope) {
if ([string]::IsNullOrEmpty($Scope)) { return $Scope }
return "=HYPERLINK(`"https://graphpermissions.merill.net/permission/$Scope`",`"Link`")"
}
# Import Functions
$FilePath = "$SCRIPT_DIR\Functions"
if (Test-Path "$FilePath")
{
if (Test-Path "$FilePath\*.ps1")
{
Get-ChildItem -Path "$FilePath" -Filter *.ps1 | ForEach-Object { . $_.FullName }
}
}
# Select Log File
if(!($Path))
{
Function Get-LogFile($InitialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.Filter = "OAuthPermissions|*-OAuthPermissions.csv|All Files (*.*)|*.*"
$OpenFileDialog.ShowDialog()
$OpenFileDialog.Filename
$OpenFileDialog.ShowHelp = $true
$OpenFileDialog.Multiselect = $false
}
$Result = Get-LogFile
if($Result -eq "OK")
{
$script:LogFile = $Result[1]
}
else
{
$Host.UI.RawUI.WindowTitle = "$DefaultWindowsTitle"
Exit
}
}
else
{
$script:LogFile = $Path
}
# Create a record of your PowerShell session to a text file
Start-Transcript -Path "$OUTPUT_FOLDER\Transcript.txt"
# Get Start Time
$startTime = (Get-Date)
# Logo
$Logo = @"
██╗ ███████╗████████╗██╗ ██╗ █████╗ ██╗ ███████╗ ██████╗ ██████╗ ███████╗███╗ ██╗███████╗██╗ ██████╗███████╗
██║ ██╔════╝╚══██╔══╝██║ ██║██╔══██╗██║ ██╔════╝██╔═══██╗██╔══██╗██╔════╝████╗ ██║██╔════╝██║██╔════╝██╔════╝
██║ █████╗ ██║ ███████║███████║██║█████╗█████╗ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║███████╗██║██║ ███████╗
██║ ██╔══╝ ██║ ██╔══██║██╔══██║██║╚════╝██╔══╝ ██║ ██║██╔══██╗██╔══╝ ██║╚██╗██║╚════██║██║██║ ╚════██║
███████╗███████╗ ██║ ██║ ██║██║ ██║███████╗ ██║ ╚██████╔╝██║ ██║███████╗██║ ╚████║███████║██║╚██████╗███████║
╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═════╝╚══════╝
"@
Write-Output ""
Write-Output "$Logo"
Write-Output ""
# Header
Write-Output "OAuthPermissions-Analyzer - Automated Processing of M365 OAuth Permissions for DFIR"
Write-Output "(c) 2026 Martin Willing at Lethal-Forensics (https://lethal-forensics.com/)"
Write-Output ""
# Analysis date (ISO 8601)
$script:AnalysisDate = [datetime]::Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")
Write-Output "Analysis date: $AnalysisDate UTC"
Write-Output ""
# Blacklists
# Create HashTable and import 'Application-Blacklist.csv'
$script:ApplicationBlacklist_HashTable = [ordered]@{}
if (Test-Path "$SCRIPT_DIR\Blacklists\Application-Blacklist.csv")
{
if(Test-Csv -Path "$SCRIPT_DIR\Blacklists\Application-Blacklist.csv" -MaxLines 2)
{
Import-Csv "$SCRIPT_DIR\Blacklists\Application-Blacklist.csv" -Delimiter "," | ForEach-Object { $ApplicationBlacklist_HashTable[$_.AppId] = $_.AppDisplayName,$_.Severity }
# Count Ingested Properties
$Count = $ApplicationBlacklist_HashTable.Count
Write-Output "[Info] Initializing 'Application-Blacklist.csv' Lookup Table ($Count) ..."
}
}
# Create HashTable and import 'ApplicationPermission-Blacklist.csv'
$script:ApplicationPermissionBlacklist_HashTable = [ordered]@{}
if (Test-Path "$SCRIPT_DIR\Blacklists\ApplicationPermission-Blacklist.csv")
{
if(Test-Csv -Path "$SCRIPT_DIR\Blacklists\ApplicationPermission-Blacklist.csv" -MaxLines 2)
{
Import-Csv "$SCRIPT_DIR\Blacklists\ApplicationPermission-Blacklist.csv" -Delimiter "," | ForEach-Object { $ApplicationPermissionBlacklist_HashTable[$_.Permission] = $_.DisplayText,$_.Severity }
# Count Ingested Properties
$Count = $ApplicationPermissionBlacklist_HashTable.Count
Write-Output "[Info] Initializing 'ApplicationPermission-Blacklist.csv' Lookup Table ($Count) ..."
}
}
# Create HashTable and import 'DelegatedPermission-Blacklist.csv'
$script:DelegatedPermissionBlacklist_HashTable = [ordered]@{}
if (Test-Path "$SCRIPT_DIR\Blacklists\DelegatedPermission-Blacklist.csv")
{
if(Test-Csv -Path "$SCRIPT_DIR\Blacklists\DelegatedPermission-Blacklist.csv" -MaxLines 2)
{
Import-Csv "$SCRIPT_DIR\Blacklists\DelegatedPermission-Blacklist.csv" -Delimiter "," | ForEach-Object { $DelegatedPermissionBlacklist_HashTable[$_.Permission] = $_.DisplayText,$_.Severity }
# Count Ingested Properties
$Count = $DelegatedPermissionBlacklist_HashTable.Count
Write-Output "[Info] Initializing 'DelegatedPermission-Blacklist.csv' Lookup Table ($Count) ..."
}
}
#endregion Header
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region Analysis
# What is OAuth?
# OAuth is open source standard that is used by web platforms to grant other platforms access to your environment. Entra ID uses OAuth to allow third party applications to integrate with your Microsoft 365 environment.
# OAuth Permissions
Function Start-Processing {
# Input-Check
if (!(Test-Path "$LogFile"))
{
Write-Host "[Error] $LogFile does not exist." -ForegroundColor Red
Write-Host ""
Stop-Transcript
$Host.UI.RawUI.WindowTitle = "$DefaultWindowsTitle"
Exit
}
# Check File Extension
$Extension = [IO.Path]::GetExtension($LogFile)
if (!($Extension -eq ".csv" ))
{
Write-Host "[Error] No CSV File provided." -ForegroundColor Red
Stop-Transcript
$Host.UI.RawUI.WindowTitle = "$DefaultWindowsTitle"
Exit
}
# Input Size
$InputSize = Get-FileSize((Get-Item "$LogFile").Length)
Write-Output "[Info] Total Input Size: $InputSize"
# Count rows of CSV (w/ thousands separators)
[int]$TotalLines = 0
$Reader = New-Object IO.StreamReader "$LogFile"
while($Reader.ReadLine() -ne $null){ $TotalLines++ }
($Reader.Dispose())
$Rows = '{0:N0}' -f $TotalLines | ForEach-Object {$_ -replace ' ','.'} # Replace Space with a dot (e.g. de-AT)
Write-Output "[Info] Total Lines: $Rows"
# Processing OAuth Permissions
Write-Output "[Info] Processing M365 OAuth Permissions ..."
New-Item "$OUTPUT_FOLDER\OAuthPermissions" -ItemType Directory -Force | Out-Null
# Custom CSV
$Data = Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Sort-Object { $_.CreatedDateTime -as [datetime] } -Descending
# https://learn.microsoft.com/en-us/graph/api/resources/serviceprincipal?view=graph-rest-1.0#properties
# https://learn.microsoft.com/en-us/graph/api/resources/oauth2permissiongrant?view=graph-rest-1.0#properties
# https://learn.microsoft.com/en-us/graph/api/resources/approleassignment?view=graph-rest-1.0#properties
# https://learn.microsoft.com/en-us/graph/api/resources/application?view=graph-rest-1.0#properties
$Results = [Collections.Generic.List[PSObject]]::new()
ForEach($Record in $Data)
{
$Description = ($Record | Select-Object @{Name='Description';Expression={if($_.Description){$_.Description}else{Get-ScopeLink $_.Permission}}}).Description
$SignInAudience = ($Record | Select-Object @{Name='SignInAudience';Expression={if($_.SignInAudience){$_.SignInAudience}else{'N/A'}}}).SignInAudience
$Line = [PSCustomObject]@{
"CreatedDateTime" = $Record | Select-Object -ExpandProperty CreatedDateTime | ForEach-Object {$_ -replace 'T',' '} | ForEach-Object {$_ -replace 'Z'} # The time when the app role assignment was created. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time.
"PermissionType" = $Record.PermissionType # Delegated access (access on behalf of a user) or App-only access (Access without a user)
"AppDisplayName" = $Record.AppDisplayName # The display name exposed by the associated application.
"AppId" = $Record.AppId # The unique identifier for the associated application.
"ClientObjectId" = $Record.ClientObjectId # The object id (not AppId) of the client service principal for the application that's authorized to act on behalf of a signed-in user when accessing an API.
"ResourceDisplayName" = $Record.ResourceDisplayName # The display name of the resource app's service principal to which the assignment is made.
"ResourceId" = $Record.ResourceObjectId # The id of the resource service principal to which access is authorized. This identifies the API that the client is authorized to attempt to call on behalf of a signed-in user.
"Permission" = $Record.Permission
"Description" = $Description
"ConsentType" = $Record.ConsentType # Indicates if authorization is granted for the client application to impersonate all users or only a specific user. AllPrincipals indicates authorization to impersonate all users. Principal indicates authorization to impersonate a specific user. Consent on behalf of all users can be granted by an administrator. Nonadmin users might be authorized to consent on behalf of themselves in some cases, for some delegated permissions.
"PrincipalDisplayName" = $Record.PrincipalDisplayName # The display name of the user, group, or service principal that was granted the app role assignment.
"PrincipalId" = $Record.PrincipalObjectId # The id of the user on behalf of whom the client is authorized to access the resource, when consentType is Principal. If consentType is AllPrincipals this value is null. Required when consentType is Principal.
"PublisherName" = $Record.PublisherName
"ExpiryTime" = $Record.ExpiryTime
"AppOwnerOrganizationId" = $Record.AppOwnerOrganizationId # Contains the tenant ID where the application is registered.
"ApplicationStatus" = $Record.ApplicationStatus # true if the service principal account is enabled; otherwise, false. If set to false, then no users are able to sign in to this app, even if they're assigned to it.
"ApplicationVisibility" = $Record.ApplicationVisibility # Hidden for the user (e.g My Apps Portal --> https://myapps.microsoft.com/)
"AssignmentRequired" = $Record.AssignmentRequired # Specifies whether users or other service principals need to be granted an app role assignment for this service principal before users can sign in or apps can get tokens.
"IsAppProxy" = $Record.IsAppProxy # Microsoft Entra ID has an application proxy service that enables users to access on-premises applications by signing in with their Microsoft Entra account.
"PublisherDisplayName" = $Record.PublisherDisplayName # The verified publisher name from the app publisher's Partner Center account.
"PublisherId" = $Record.VerifiedPublisherId # The ID of the verified publisher from the app publisher's Partner Center account.
"LastUpdated" = $Record.AddedDateTime # The timestamp when the verified publisher was first added or most recently updated.
"SignInAudience" = $SignInAudience # Specifies the Microsoft accounts that are supported for the current application. Read-only.
"ApplicationType" = $Record.ApplicationType # Identifies whether the service principal represents an application, a managed identity, or a legacy application. This is set by Microsoft Entra ID internally.
"Homepage" = $Record.Homepage # Home page or landing page of the application.
"ReplyUrls" = $Record.ReplyUrls # The URLs that user tokens are sent to for sign in with the associated application, or the redirect URIs that OAuth 2.0 authorization codes and access tokens are sent to for the associated application.
"IsEnabled" = $Record.IsEnabled
}
$Results.Add($Line)
}
$Results | Export-Csv -Path "$OUTPUT_FOLDER\OAuthPermissions\OAuthPermissions.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\OAuthPermissions\OAuthPermissions.csv")
{
if(Test-Csv -Path "$OUTPUT_FOLDER\OAuthPermissions\OAuthPermissions.csv" -MaxLines 2)
{
$Import = Import-Csv -Path "$OUTPUT_FOLDER\OAuthPermissions\OAuthPermissions.csv" -Delimiter "," -Encoding UTF8
# LETHAL-001: AppDisplayName with only non-alphanumeric characters
[array]$RegEx01 = $Import | Where-Object { $_.AppDisplayName -match "^[^a-zA-Z0-9]+$" } | Select-Object -ExpandProperty AppDisplayName
$Count = ($RegEx01 | Select-Object AppId -Unique | Measure-Object).Count
if ($Count -gt 0)
{
Write-Host "[Alert] Suspicious OAuth Application detected: AppDisplayName w/ only non-alphanumeric characters ($Count)" -ForegroundColor Red
}
# LETHAL-002: Anomalous ReplyUrls including a local loopback URL
[array]$RegEx02 = $Import | Where-Object { $_.ReplyUrls -match "http://localhost:\d+/access/?" } | Select-Object -ExpandProperty ReplyUrls
$Count = ($RegEx02 | Select-Object AppId -Unique | Measure-Object).Count
if ($Count -gt 0)
{
Write-Host "[Alert] Suspicious OAuth Application detected: Anomalous ReplyUrl including a local loopback URL ($Count)" -ForegroundColor Red
}
# LETHAL-003: Common Naming Patterns of Malicious OAuth Applications
[array]$RegEx03 = $Import | Where-Object { $_.AppDisplayName -match "^(test|test app|app test|apptest)$" } | Select-Object -ExpandProperty AppDisplayName
$Count = ($RegEx03 | Select-Object AppId -Unique | Measure-Object).Count
if ($Count -gt 0)
{
Write-Host "[Alert] Suspicious OAuth Application detected: Common Naming Pattern of Malicious OAuth Applications ($Count)" -ForegroundColor Red
}
# LETHAL-004: UPN Naming Pattern (incl. B2B Collaboration User)
[array]$RegEx04 = $Import | Where-Object { $_.AppDisplayName -match "^([\w-\.]+)(#EXT#)?@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" } | Select-Object -ExpandProperty AppDisplayName
$Count = ($RegEx04 | Select-Object AppId -Unique | Measure-Object).Count
if ($Count -gt 0)
{
Write-Host "[Alert] Suspicious OAuth Application detected: UPN Naming Pattern ($Count)" -ForegroundColor Red
}
# LETHAL-005: User Naming Pattern (PrincipalDisplayName)
[array]$PrincipalDisplayNames = $Import | Where-Object {$_.PrincipalDisplayName -ne ""} | Select-Object -ExpandProperty PrincipalDisplayName -Unique
$Principals = @()
foreach ($PrincipalDisplayName in $PrincipalDisplayNames)
{
$Principals += $Import | Where-Object { $_.AppDisplayName -eq "$PrincipalDisplayName" } | Select-Object -ExpandProperty AppDisplayName -Unique
}
$Count = ($Principals | Select-Object AppId -Unique | Measure-Object).Count
if ($Count -gt 0)
{
Write-Host "[Alert] Suspicious OAuth Application detected: User Naming Pattern ($Count)" -ForegroundColor Red
}
$Import | Export-Excel -Path "$OUTPUT_FOLDER\OAuthPermissions\OAuthPermissions.xlsx" -NoHyperLinkConversion * -FreezePane 2,5 -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "OAuthPermissions" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
Set-Format -Address $WorkSheet.Cells["A1:Z1"] -BackgroundColor $BackgroundColor -FontColor $FontColor
# HorizontalAlignment "Center" of columns A-Y
$WorkSheet.Cells["A:Y"].Style.HorizontalAlignment="Center"
# Font Style "Underline" of column I (Link)
Add-ConditionalFormatting -Address $WorkSheet.Cells["I:I"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Link",$I1)))' -Underline
# ConditionalFormatting - AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["C:C"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(SEARCH("LethalForensics_IR-App",$C1)))' -BackgroundColor $Green
foreach ($AppDisplayName in $RegEx01)
{
$ConditionValue = 'EXACT("{0}",$C1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["C:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx01
}
foreach ($AppDisplayName in $RegEx03)
{
$ConditionValue = 'EXACT("{0}",$C1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["C:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx03
}
foreach ($AppDisplayName in $RegEx04)
{
$ConditionValue = 'EXACT("{0}",$C1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["C:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx04
}
foreach ($PrincipalDisplayName in $PrincipalDisplayNames)
{
$ConditionValue = 'EXACT("{0}",$C1)' -f $PrincipalDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["C:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # PrincipalDisplayName
}
# ConditionalFormatting - AppId
Add-ConditionalFormatting -Address $WorkSheet.Cells["C:D"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("fb4c470b-9133-42c7-8db0-f786adc04715",$D1)))' -BackgroundColor $Green # Invictus Cloud Insights
# ConditionalFormatting - AppOwnerOrganizationId
Add-ConditionalFormatting -Address $WorkSheet.Cells["O:O"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("72f988bf-86f1-41af-91ab-2d7cd011db47",$O1)))' -BackgroundColor $Green # Microsoft Application
Add-ConditionalFormatting -Address $WorkSheet.Cells["O:O"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("f8cdef31-a31e-4b4a-93e4-5f571e91255a",$O1)))' -BackgroundColor $Green # Microsoft Application
# ConditionalFormatting - PublisherName
Add-ConditionalFormatting -Address $WorkSheet.Cells["T:T"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("eM Client s.r.o.",$T1)))' -BackgroundColor Red # eM Client
# ConditionalFormatting - ReplyUrls
foreach ($ReplyUrl in $RegEx02)
{
$ConditionValue = 'EXACT("{0}",$Z1)' -f $ReplyUrl
Add-ConditionalFormatting -Address $WorkSheet.Cells["Z:Z"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx02
}
# LETHAL-006: Iterating over the Application-Blacklist HashTable
foreach ($AppId in $ApplicationBlacklist_HashTable.Keys)
{
$Severity = $ApplicationBlacklist_HashTable["$AppId"][1]
$ConditionValue = 'NOT(ISERROR(FIND("{0}",$D1)))' -f $AppId
Add-ConditionalFormatting -Address $WorkSheet.Cells["C:D"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor $Severity
}
# Iterating over the Application-Blacklist HashTable
[int]$Matches = "0"
foreach ($AppId in $ApplicationBlacklist_HashTable.Keys)
{
$Count = ($Import | Where-Object { $_.AppId -eq "$AppId" } | Measure-Object).Count
if ($Count -gt 0)
{
$Matches++
$AppDisplayName = $ApplicationBlacklist_HashTable["$AppId"][0]
$Severity = $ApplicationBlacklist_HashTable["$AppId"][1]
Write-Host "[Alert] Suspicious OAuth Application detected: $AppDisplayName ($Count)" -ForegroundColor $Severity
}
}
# Count Matches
if ($Matches -eq "0")
{
Write-Host "[Info] No blacklisted Application (Traitorware) found." -ForegroundColor Green
}
# Iterating over the ApplicationPermission-Blacklist HashTable
foreach ($Permission in $ApplicationPermissionBlacklist_HashTable.Keys)
{
$Severity = $ApplicationPermissionBlacklist_HashTable["$Permission"][1]
if ($Severity -eq "High"){$BackgroundColor = $HighColor}
if ($Severity -eq "Medium"){$BackgroundColor = $MediumColor}
if ($Severity -eq "Low"){$BackgroundColor = $LowColor}
$ConditionValue = '=AND($B1="Application",$H1="{0}")' -f $Permission
Add-ConditionalFormatting -Address $WorkSheet.Cells["H:H"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor $BackgroundColor
}
# Iterating over the DelegatedPermission-Blacklist HashTable
foreach ($Permission in $DelegatedPermissionBlacklist_HashTable.Keys)
{
$Severity = $DelegatedPermissionBlacklist_HashTable["$Permission"][1]
if ($Severity -eq "High"){$BackgroundColor = $HighColor}
if ($Severity -eq "Medium"){$BackgroundColor = $MediumColor}
if ($Severity -eq "Low"){$BackgroundColor = $LowColor}
$ConditionValue = '=AND($B1="Delegated",$H1="{0}")' -f $Permission
Add-ConditionalFormatting -Address $WorkSheet.Cells["H:H"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor $BackgroundColor
}
}
}
}
# OAuthApps
$ClientObjectId = (Import-Csv -Path "$LogFile" -Delimiter "," | Select-Object ClientObjectId -Unique | Measure-Object).Count
$ClientObjectIdCount = '{0:N0}' -f $ClientObjectId
$AppDisplayName = (Import-Csv -Path "$LogFile" -Delimiter "," | Select-Object AppDisplayName -Unique | Measure-Object).Count
$AppDisplayNameCount = '{0:N0}' -f $AppDisplayName
Write-Output "[Info] $ClientObjectIdCount OAuth Applications found (AppDisplayName: $AppDisplayNameCount)"
# PermissionType
[int]$Delegated = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object { $_.PermissionType -eq "Delegated" } | Measure-Object).Count
[int]$Application = (Import-Csv -Path "$LogFile" -Delimiter "," -Encoding UTF8 | Where-Object { $_.PermissionType -eq "Application" } | Measure-Object).Count
$DelegatedCount = '{0:N0}' -f $Delegated
$ApplicationCount = '{0:N0}' -f $Application
Write-Output "[Info] $DelegatedCount Delegated Permissions and $ApplicationCount Application Permissions found"
# Application Permissions (AppRoleAssignments) vs. Delegated Permissions (OAuth2PermissionGrants)
# Microsoft 365 has two types of OAuth permissions: application permissions and delegated permissions. They often have similar or even identical names, but the difference is important because the scope of each permission type varies considerably.
# - Application permissions grant tenant-wide access to the permission requested. For example, an app that has been granted the application permissions Mail.Read and Files.Read.All can read all user mail and read all files. For obvious reasons, application permissions can only be granted by an admin.
# - Delegated Permissions grant the app access as that user within the confines of the permissions requested. For example, an app that has been granted the delegated permission Mail.Read can read the mail of the user who consented to the app.
# By default in Microsoft Entra ID, all users can register applications and manage all aspects of applications they create. Everyone also has the ability to consent to apps accessing company data on their behalf.
# https://learn.microsoft.com/en-us/azure/active-directory/roles/delegate-app-roles
# Create Application Registrations
# 1. Sign in to the Microsoft Entra admin center as a Global Administrator.
# 2. Browse to Identity > Users > User settings.
# 3. Set the Users can register applications setting to No.
# --> This will disable the default ability for users to create application registrations.
# Consent to applications
# 1. Browse to Identity > Enterprise applications > Consent and permissions.
# 2. Select the "Do not allow user consent" option.
# --> This will disable the default ability for users to consent to applications accessing company data on their behalf.
# File Size (XLSX)
if (Test-Path "$OUTPUT_FOLDER\OAuthPermissions\OAuthPermissions.xlsx")
{
$Size = Get-FileSize((Get-Item "$OUTPUT_FOLDER\OAuthPermissions\OAuthPermissions.xlsx").Length)
Write-Output "[Info] File Size (XLSX): $Size"
}
# ConsentType
# Principal - Grant consent on behalf of a single user
# AllPrincipals - Grant consent on behalf of your organization
# Application Permissions --> ...without a signed-in user
# Name - This is the name of the application that users see on 'My Apps', admins see when managing access to this app, or other tenants see when integrating this app into their directory.
# AppId - This is the unique application ID of this application in your directory. You can use this application ID if you ever need help from Microsoft Support, or if you want to perform operations against this specific instance of the application using Microsoft Graph or PowerShell APIs.
# ObjectId - This is the unique ID of the service principal object associated with this application. This ID can be useful when performing management operations against this application using PowerShell or other programmatic interfaces.
# AccountEnabled (Enabled for users to sign-in?) - If this option is set to yes, then assigned users will be able to sign in to this application, either from My Apps, the User access URL, or by navigating to the application URL directly. If this option is set to no, then no users will be able to sign in to this app, even if they are assigned to it.
# AppRoleAssignmentRequired (Assignment required?) - If this option is set to yes, then users and other apps or services must first be assigned to this application before being able to access it. If this option is set to no, then all users will be able to sign in, and other apps and services will be able to obtain an access token to this service.
# ApplicationVisibility (Visible to users?) - If this option is set to yes, then assigned users will see the application on My Apps and O365 app launcher. If this option is set to no, then no users will see this application on their My Apps and O365 launcher.
# SignInAudience - Specifies the Microsoft accounts that are supported for the current application. Read-only.
# - AzureADMyOrg: Users with a Microsoft work or school account in my organization's Microsoft Entra tenant (single-tenant).
# - AzureADMultipleOrgs: Users with a Microsoft work or school account in any organization's Microsoft Entra tenant (multitenant).
# - AzureADandPersonalMicrosoftAccount: Users with a personal Microsoft account, or a work or school account in any organization's Microsoft Entra tenant.
# - PersonalMicrosoftAccount: Users with a personal Microsoft account only.
# Account Types
# Who can use this application or access this API?
# 1. Accounts in this organizational directory only (Lethal Company only - Single tenant)
# 2. Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant)
# 3. Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)
# 4. Personal Microsoft accounts only
# Understanding Different Account Types
# 1. Accounts in this organizational directory only (Lethal Company only - Single tenant)
# All user and guest accounts in your directory can use your application or API.
# Use this option if your target audience is internal to your organization.
# 2. Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant)
# All users with a work or school account from Microsoft can use your application or API. This includes schools and businesses that use Office 365.
# Use this option if your target audience is business or educational customers and to enable multitenancy.
# 3. Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)
# All users with a work or school, or personal Microsoft account can use your application or API. It includes schools and businesses that use Office 365 as well as personal accounts that are used to sign in to services like Xbox and Skype.
# Use this option to target the widest set of Microsoft identities and to enable multitenancy.
# 4. Personal Microsoft accounts only
# Personal accounts that are used to sign in to services like Xbox and Skype.
# Use this option to target the widest set of Microsoft identities.
# ServicePrincipalType - Identifies whether the service principal represents an application, a managed identity, or a legacy application. This is set by Microsoft Entra ID internally.
# - Application - A service principal that represents an application or service. The appId property identifies the associated app registration, and matches the appId of an application, possibly from a different tenant. If the associated app registration is missing, tokens aren't issued for the service principal.
# - ManagedIdentity - A service principal that represents a managed identity. Service principals representing managed identities can be granted access and permissions, but can't be updated or modified directly.
# - Legacy - A service principal that represents an app created before app registrations, or through legacy experiences. A legacy service principal can have credentials, service principal names, reply URLs, and other properties that are editable by an authorized user, but doesn't have an associated app registration. The appId value doesn't associate the service principal with an app registration. The service principal can only be used in the tenant where it was created.
# Enterprise Applications shows non-Microsoft applications.
# Microsoft Applications shows Microsoft applications.
# Managed Identities shows applications that are used to authenticate to services that support Microsoft Entra authentication.
#############################################################################################################################################################################################
# Stats
New-Item "$OUTPUT_FOLDER\OAuthPermissions\Stats" -ItemType Directory -Force | Out-Null
# Import Data
$Data = Import-Csv -Path "$OUTPUT_FOLDER\OAuthPermissions\OAuthPermissions.csv" -Delimiter "," -Encoding UTF8
# AppOwnerOrganizationId (Stats)
$Total = ($Data | Select-Object AppOwnerOrganizationId | Measure-Object).Count
if ($Total -ge "1")
{
$Stats = $Data | Group-Object AppOwnerOrganizationId | Select-Object @{Name='AppOwnerOrganizationId'; Expression={ $_.Values[0] }},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending
$Stats | Export-Excel -Path "$OUTPUT_FOLDER\OAuthPermissions\Stats\AppOwnerOrganizationId.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "AppOwnerOrganizationId" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor $FontColor
# HorizontalAlignment "Center" of columns A-C
$WorkSheet.Cells["A:C"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - AppOwnerOrganizationId
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("72f988bf-86f1-41af-91ab-2d7cd011db47",$A1)))' -BackgroundColor $Green # Microsoft Application
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("f8cdef31-a31e-4b4a-93e4-5f571e91255a",$A1)))' -BackgroundColor $Green # Microsoft Application
}
}
# AppDisplayName (Stats)
$Applications = ($Data | Select-Object AppDisplayName -Unique | Sort-Object AppDisplayName).AppDisplayName
$Stats = [Collections.Generic.List[PSObject]]::new()
ForEach($App in $Applications)
{
$Count = ($Data | Where-Object {$_.AppDisplayName -eq "$App"} | Select-Object PrincipalDisplayName -Unique | Measure-Object).Count
$ConsentType = ($Data | Where-Object {$_.AppDisplayName -eq "$App"} | Select-Object -ExpandProperty ConsentType -Unique | Sort-Object) -join ", "
$Line = [PSCustomObject]@{
"AppDisplayName" = $App
"ConsentType" = $ConsentType
"Count" = $Count
}
$Stats.Add($Line)
}
# XLSX
$Stats | Export-Excel -Path "$OUTPUT_FOLDER\OAuthPermissions\Stats\AppDisplayName-ConsentType.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "AppDisplayName" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor $FontColor
# HorizontalAlignment "Center" of column B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Invictus Cloud Insights",$A1)))' -BackgroundColor $Green
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("LethalForensics_IR-App",$A1)))' -BackgroundColor $Green
foreach ($AppDisplayName in $RegEx01)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx01
}
foreach ($AppDisplayName in $RegEx03)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx03
}
foreach ($AppDisplayName in $RegEx04)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx04
}
foreach ($PrincipalDisplayName in $PrincipalDisplayNames)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $PrincipalDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # PrincipalDisplayName
}
}
# AppDisplayName / AppId (Stats)
$Applications = ($Data | Select-Object AppId -Unique | Sort-Object AppId).AppId
$Stats = [Collections.Generic.List[PSObject]]::new()
ForEach($App in $Applications)
{
$Count = ($Data | Where-Object {$_.AppId -eq "$App"} | Select-Object PrincipalDisplayName -Unique | Measure-Object).Count
$AppDisplayName = $Data | Where-Object {$_.AppId -eq "$App"} | Select-Object AppDisplayName -Unique
$Line = [PSCustomObject]@{
"AppDisplayName" = $AppDisplayName.AppDisplayName
"AppId" = $App
"Count" = $Count
}
$Stats.Add($Line)
}
# XLSX
$Stats | Sort-Object AppDisplayName | Export-Excel -Path "$OUTPUT_FOLDER\OAuthPermissions\Stats\AppDisplayName-AppId.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Applications" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor $FontColor
# HorizontalAlignment "Center" of column B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("LethalForensics_IR-App",$A1)))' -BackgroundColor $Green
foreach ($AppDisplayName in $RegEx01)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx01
}
foreach ($AppDisplayName in $RegEx03)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx03
}
foreach ($AppDisplayName in $RegEx04)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx04
}
foreach ($PrincipalDisplayName in $PrincipalDisplayNames)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $PrincipalDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # PrincipalDisplayName
}
# ConditionalFormatting - AppId
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(SEARCH("fb4c470b-9133-42c7-8db0-f786adc04715",$B1)))' -BackgroundColor $Green # Invictus Cloud Insights
# Iterating over the Application-Blacklist HashTable
foreach ($AppId in $ApplicationBlacklist_HashTable.Keys)
{
$Severity = $ApplicationBlacklist_HashTable["$AppId"][1]
$ConditionValue = 'NOT(ISERROR(FIND("{0}",$B1)))' -f $AppId
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor $Severity
}
}
# AppDisplayName / AppId / AppOwnerOrganizationId (Stats)
$Data = Import-Csv -Path "$OUTPUT_FOLDER\OAuthPermissions\OAuthPermissions.csv" -Delimiter "," -Encoding UTF8
$Total = ($Data | Select-Object AppId | Measure-Object).Count
if ($Total -ge "1")
{
$Stats = $Data | Group-Object AppDisplayName,AppId,AppOwnerOrganizationId | Select-Object @{Name='AppDisplayName'; Expression={ $_.Values[0] }},@{Name='AppId'; Expression={ $_.Values[1] }},@{Name='AppOwnerOrganizationId'; Expression={ $_.Values[2] }},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}}
$Stats | Export-Excel -Path "$OUTPUT_FOLDER\OAuthPermissions\Stats\AppDisplayName-AppId-AppOwnerOrganizationId.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Applications" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
Set-Format -Address $WorkSheet.Cells["A1:E1"] -BackgroundColor $BackgroundColor -FontColor $FontColor
# HorizontalAlignment "Center" of column B-E
$WorkSheet.Cells["B:E"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:E"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("LethalForensics_IR-App",$A1)))' -BackgroundColor $Green
foreach ($AppDisplayName in $RegEx01)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:E"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx01
}
foreach ($AppDisplayName in $RegEx03)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:E"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx03
}
foreach ($AppDisplayName in $RegEx04)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:E"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx04
}
foreach ($PrincipalDisplayName in $PrincipalDisplayNames)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $PrincipalDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:E"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # PrincipalDisplayName
}
# ConditionalFormatting - AppId
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:E"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(SEARCH("fb4c470b-9133-42c7-8db0-f786adc04715",$B1)))' -BackgroundColor $Green # Invictus Cloud Insights
# Iterating over the Application-Blacklist HashTable
foreach ($AppId in $ApplicationBlacklist_HashTable.Keys)
{
$Severity = $ApplicationBlacklist_HashTable["$AppId"][1]
$ConditionValue = 'NOT(ISERROR(FIND("{0}",$B1)))' -f $AppId
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:E"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor $Severity
}
}
}
# AppDisplayName / AppId / AppOwnerOrganizationId / ApplicationType (Stats)
$Applications = ($Data | Select-Object AppId -Unique | Sort-Object AppId).AppId
$Stats = [Collections.Generic.List[PSObject]]::new()
ForEach($AppId in $Applications)
{
$AppDisplayName = $Data | Where-Object {$_.AppId -eq "$AppId"} | Select-Object -ExpandProperty AppDisplayName -Unique
$AppOwnerOrganizationId = $Data | Where-Object {$_.AppId -eq "$AppId"} | Select-Object -ExpandProperty AppOwnerOrganizationId -Unique
if ($AppOwnerOrganizationId -eq "72f988bf-86f1-41af-91ab-2d7cd011db47" -or $AppOwnerOrganizationId -eq "f8cdef31-a31e-4b4a-93e4-5f571e91255a")
{
$ApplicationType = "First-Party Application" # Microsoft Application
}
else
{
$ApplicationType = "Third-Party Application"
}
$Line = [PSCustomObject]@{
"AppDisplayName" = $AppDisplayName
"AppId" = $AppId
"AppOwnerOrganizationId" = $AppOwnerOrganizationId
"ApplicationType" = $ApplicationType
}
$Stats.Add($Line)
}
# XLSX
$Stats | Sort-Object AppDisplayName | Export-Excel -Path "$OUTPUT_FOLDER\OAuthPermissions\Stats\AppDisplayName-AppId-AppOwnerOrganizationId-ApplicationType.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Applications" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
Set-Format -Address $WorkSheet.Cells["A1:D1"] -BackgroundColor $BackgroundColor -FontColor $FontColor
# HorizontalAlignment "Center" of column B-D
$WorkSheet.Cells["B:D"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:D"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("LethalForensics_IR-App",$A1)))' -BackgroundColor $Green
foreach ($AppDisplayName in $RegEx01)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:D"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx01
}
foreach ($AppDisplayName in $RegEx03)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:D"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx03
}
foreach ($AppDisplayName in $RegEx04)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:D"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # RegEx04
}
foreach ($PrincipalDisplayName in $PrincipalDisplayNames)
{
$ConditionValue = 'EXACT("{0}",$A1)' -f $PrincipalDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:D"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor Red # PrincipalDisplayName
}
# ConditionalFormatting - AppId
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:D"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(SEARCH("fb4c470b-9133-42c7-8db0-f786adc04715",$B1)))' -BackgroundColor $Green # Invictus Cloud Insights
# Iterating over the Application-Blacklist HashTable
foreach ($AppId in $ApplicationBlacklist_HashTable.Keys)
{
$Severity = $ApplicationBlacklist_HashTable["$AppId"][1]
$ConditionValue = 'NOT(ISERROR(FIND("{0}",$B1)))' -f $AppId
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:D"] -WorkSheet $WorkSheet -RuleType 'Expression' -ConditionValue $ConditionValue -BackgroundColor $Severity
}
}
# ClientObjectId (Stats)
$ClientObjectIds = ($Data | Select-Object ClientObjectId -Unique | Sort-Object ClientObjectId).ClientObjectId
$Stats = [Collections.Generic.List[PSObject]]::new()
ForEach($Id in $ClientObjectIds)
{
$Name = $Data | Where-Object {$_.ClientObjectId -eq "$Id"} | Select-Object -ExpandProperty AppDisplayName -Unique
$Count = ($Data | Where-Object {$_.ClientObjectId -eq "$Id"} | Select-Object PrincipalDisplayName -Unique | Measure-Object).Count
$Line = [PSCustomObject]@{
"AppDisplayName" = $Name
"ClientObjectId" = $Id
"Users" = $Count
}
$Stats.Add($Line)
}
# XLSX
$Stats | Sort-Object AppDisplayName | Export-Excel -Path "$OUTPUT_FOLDER\OAuthPermissions\Stats\ClientObjectId.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "ClientObjectId" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor $FontColor
# HorizontalAlignment "Center" of column B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - AppDisplayName
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Invictus Cloud Insights",$A1)))' -BackgroundColor $Green
Add-ConditionalFormatting -Address $WorkSheet.Cells["A:C"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("LethalForensics_IR-App",$A1)))' -BackgroundColor $Green