-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathServicePrincipal-Analyzer.ps1
More file actions
2343 lines (2034 loc) · 151 KB
/
ServicePrincipal-Analyzer.ps1
File metadata and controls
2343 lines (2034 loc) · 151 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
# ServicePrincipal-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
#
# IPinfo CLI 3.3.1 (2024-03-01)
# https://ipinfo.io/signup?ref=cli --> Sign up for free
# https://github.com/ipinfo/cli
#
#
# 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
ServicePrincipal-Analyzer - Automated Processing of Microsoft Service Principal Sign-In Logs for DFIR
.DESCRIPTION
ServicePrincipal-Analyzer.ps1 is a PowerShell script utilized to simplify the analysis of Microsoft Service Principal Sign-In Logs 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/AzureSignInLogsGraph.html
.PARAMETER OutputDir
Specifies the output directory. Default is "$env:USERPROFILE\Desktop\ServicePrincipal-Analyzer".
Note: The subdirectory 'ServicePrincipal-Analyzer' is automatically created.
.PARAMETER Path
Specifies the path to the JSON-based input file (SignInLogs-servicePrincipal-Combined.json).
.EXAMPLE
PS> .\ServicePrincipal-Analyzer.ps1
.EXAMPLE
PS> .\ServicePrincipal-Analyzer.ps1 -Path "$env:USERPROFILE\Desktop\SignInLogs-servicePrincipal-Combined.json"
.EXAMPLE
PS> .\ServicePrincipal-Analyzer.ps1 -Path "H:\Microsoft-Extractor-Suite\SignInLogs-servicePrincipal-Combined.json" -OutputDir "H:\Microsoft-Analyzer-Suite"
.NOTES
Author - Martin Willing
.LINK
https://lethal-forensics.com/
#>
#############################################################################################################################################################################################
#############################################################################################################################################################################################
# How long does Microsoft Entra ID store the Sign-ins data?
# Microsoft Entra ID Free 7 days
# Microsoft Entra ID P1 30 days
# Microsoft Entra ID P2 30 days
# Note: You must have a Microsoft Entra ID P1 or P2 license to download sign-in logs using the Microsoft Graph API.
# Workload Identities
# Service principal sign-ins are the authentication events for a service principal, which is a type of workload identity used by an application to access resources.
# https://learn.microsoft.com/en-us/entra/workload-id/workload-identities-overview
#
# - non-interactive sign-ins
# - Can’t perform multifactor authentication (MFA) --> Basic Authentication
# - Usually with high privileges
# - Conditional Access Policies (Microsoft Entra ID P1 or P2) do not cover service principal sign-ins (apply only to users when they access apps and services) --> Microsoft Entra Workload ID Premium required
# - Full risk details and risk-based access controls are available to Workload Identities Premium customers only. However, customers without the Workload Identities Premium licenses still receive all detections with limited reporting details.
#
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region CmdletBinding
[CmdletBinding()]
Param(
[String]$Path,
[String]$OutputDir
)
#endregion CmdletBinding
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region Initialisations
# Set Progress Preference to Silently Continue
$OriginalProgressPreference = $Global:ProgressPreference
$Global:ProgressPreference = 'SilentlyContinue'
#endregion Initialisations
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#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\ServicePrincipal-Analyzer" # Default
}
else
{
if ($OutputDir -cnotmatch '.+(?=\\)')
{
Write-Host "[Error] You must provide a valid directory path." -ForegroundColor Red
Exit
}
else
{
$script:OUTPUT_FOLDER = "$OutputDir\ServicePrincipal-Analyzer" # Custom
}
}
# Tools
# IPinfo CLI
$script:IPinfo = "$SCRIPT_DIR\Tools\IPinfo\ipinfo.exe"
# Import Functions
$FilePath = "$SCRIPT_DIR\Functions"
if (Test-Path "$FilePath")
{
if (Test-Path "$FilePath\*.ps1")
{
Get-ChildItem -Path "$FilePath" -Filter *.ps1 | ForEach-Object { . $_.FullName }
}
}
# 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/LETHAL-FORENSICS/Microsoft-Analyzer-Suite/wiki#setup"
Exit
}
# Windows Title
$DefaultWindowsTitle = $Host.UI.RawUI.WindowTitle
$Host.UI.RawUI.WindowTitle = "ServicePrincipal-Analyzer - Automated Processing of Microsoft Service Principal Sign-In Logs for DFIR"
# 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
# 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 = "Sign-In Logs|SignInLogs-servicePrincipal-Combined.json|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 "ServicePrincipal-Analyzer - Automated Processing of Microsoft Service Principal Sign-In Logs 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 ""
# 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) ..."
}
}
else
{
Write-Host "[Error] 'Application-Blacklist.csv' NOT found." -ForegroundColor Red
}
# Create HashTable and import 'ASN-Blacklist.csv'
$script:AsnBlacklist_HashTable = [ordered]@{}
if (Test-Path "$SCRIPT_DIR\Blacklists\ASN-Blacklist.csv")
{
if(Test-Csv -Path "$SCRIPT_DIR\Blacklists\ASN-Blacklist.csv" -MaxLines 2)
{
Import-Csv "$SCRIPT_DIR\Blacklists\ASN-Blacklist.csv" -Delimiter "," | ForEach-Object { $AsnBlacklist_HashTable[$_.ASN] = $_.OrgName,$_.Info }
# Count Ingested Properties
$Count = $AsnBlacklist_HashTable.Count
Write-Output "[Info] Initializing 'ASN-Blacklist.csv' Lookup Table ($Count) ..."
}
}
else
{
Write-Host "[Error] 'ASN-Blacklist.csv' NOT found." -ForegroundColor Red
}
# Create HashTable and import 'Country-Blacklist.csv'
$script:CountryBlacklist_HashTable = [ordered]@{}
if (Test-Path "$SCRIPT_DIR\Blacklists\Country-Blacklist.csv")
{
if(Test-Csv -Path "$SCRIPT_DIR\Blacklists\Country-Blacklist.csv" -MaxLines 2)
{
Import-Csv "$SCRIPT_DIR\Blacklists\Country-Blacklist.csv" -Delimiter "," | ForEach-Object { $CountryBlacklist_HashTable[$_."Country Name"] = $_.Country }
# Count Ingested Properties
$Count = $CountryBlacklist_HashTable.Count
Write-Output "[Info] Initializing 'Country-Blacklist.csv' Lookup Table ($Count) ..."
}
}
else
{
Write-Host "[Error] 'Country-Blacklist.csv' NOT found." -ForegroundColor Red
}
# Create HashTable and import 'UserAgent-Blacklist.csv'
$script:UserAgentBlacklist_HashTable = New-Object System.Collections.Hashtable
if (Test-Path "$SCRIPT_DIR\Blacklists\UserAgent-Blacklist.csv")
{
if(Test-Csv -Path "$SCRIPT_DIR\Blacklists\UserAgent-Blacklist.csv" -MaxLines 2)
{
Import-Csv "$SCRIPT_DIR\Blacklists\UserAgent-Blacklist.csv" -Delimiter "," | ForEach-Object { $UserAgentBlacklist_HashTable[$_.UserAgent] = $_.Category,$_.Severity }
# Count Ingested Properties
$Count = $UserAgentBlacklist_HashTable.Count
Write-Output "[Info] Initializing 'UserAgent-Blacklist.csv' Lookup Table ($Count) ..."
}
}
else
{
Write-Host "[Error] 'UserAgent-Blacklist.csv' NOT found." -ForegroundColor Red
}
#endregion Header
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region Analysis
# Microsoft Service Principal Sign-In Logs (App-Only Context)
# https://learn.microsoft.com/en-us/entra/identity/monitoring-health/concept-service-principal-sign-ins
# What are service principal sign-ins in Microsoft Entra?
# Unlike interactive and non-interactive user sign-ins, service principal sign-ins don't involve a user.
# Instead, they're sign-ins by any non-user account, such as apps or service principals (except managed identity sign-in, which are in included only in the managed identity sign-in log).
# In these sign-ins, the app or service provides its own credential, such as a certificate or app secret to authenticate or access resources.
Function Start-Processing {
$StartTime_Processing = (Get-Date)
# 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 ".json" ))
{
Write-Host "[Error] No JSON File provided." -ForegroundColor Red
Write-Host ""
Stop-Transcript
$Host.UI.RawUI.WindowTitle = "$DefaultWindowsTitle"
Exit
}
# Check IPinfo CLI Access Token
if ("$Token" -eq "access_token")
{
Write-Host "[Error] No IPinfo CLI Access Token provided. Please add your personal access token to 'Config.json'" -ForegroundColor Red
Write-Host ""
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 JSON (w/ thousands separators)
$Count = 0
switch -File "$LogFile" { default { ++$Count } }
$Rows = '{0:N0}' -f $Count
Write-Output "[Info] Total Lines: $Rows"
# Processing Microsoft Entra ID Sign-In Logs
Write-Output "[Info] Processing Microsoft Service Principal Sign-In Logs ..."
New-Item "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\CSV" -ItemType Directory -Force | Out-Null
New-Item "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\XLSX" -ItemType Directory -Force | Out-Null
# Import JSON
$Data = Get-Content -Path "$LogFile" -Raw | ConvertFrom-Json | Sort-Object { $_.createdDateTime -as [datetime] } -Descending
# Time Frame
$Last = ($Data | Sort-Object { $_.createdDateTime -as [datetime] } -Descending | Select-Object -Last 1).createdDateTime
$First = ($Data | Sort-Object { $_.createdDateTime -as [datetime] } -Descending | Select-Object -First 1).createdDateTime
$StartDate = (Get-Date $Last).ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")
$EndDate = (Get-Date $First).ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")
Write-Output "[Info] Log data from $StartDate UTC until $EndDate UTC"
# Untouched
# https://learn.microsoft.com/en-us/powershell/module/Microsoft.Graph.Beta.Reports/Get-MgBetaAuditLogSignIn?view=graph-powershell-beta
# https://learn.microsoft.com/nb-no/graph/api/resources/signin?view=graph-rest-beta
# CSV
$Results = [Collections.Generic.List[PSObject]]::new()
ForEach($Record in $Data)
{
$CreatedDateTime = $Record | Select-Object -ExpandProperty createdDateTime
$NetworkLocationDetails = $Record | Select-Object -ExpandProperty networkLocationDetails
$NetworkNames = ($NetworkLocationDetails | Select-Object -ExpandProperty networkNames) -join ", "
$NetworkType = ($NetworkLocationDetails | Select-Object -ExpandProperty networkType) -join "`r`n"
# TrustedNamedLocation
if ($NetworkType | Select-String -Pattern "trustedNamedLocation" -Quiet)
{
$TrustedNamedLocation = "Yes"
}
else
{
$TrustedNamedLocation = "No"
}
$Line = [PSCustomObject]@{
"Id" = $Record.Id # The identifier representing the sign-in activity.
"CreatedDateTime" = (Get-Date $CreatedDateTime).ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")
"AppId" = $Record.appId # The application identifier in Microsoft Entra ID.
"AppDisplayName" = $Record.appDisplayName # The application name displayed in the Microsoft Entra admin center.
"AppOwnerTenantId" = $Record.appOwnerTenantId # The identifier of the tenant that owns the client application.
"ResourceOwnerTenantId" = $Record.resourceOwnerTenantId # The identifier of the owner of the resource.
"ServicePrincipalId" = $Record.servicePrincipalId # The application identifier used for sign-in.
"ServicePrincipalName" = $Record.servicePrincipalName # The application name used for sign-in.
"ClientAppUsed" = $Record.clientAppUsed # The legacy client used for sign-in activity.
"UserAgent" = $Record.userAgent # The user agent information related to sign-in.
"IPAddress" = $Record.ipAddress # The IP address of the client from where the sign-in occurred.
"ASN" = $Record.AutonomousSystemNumber # The Autonomous System Number (ASN) of the network used by the actor.
"City" = $Record | Select-Object -ExpandProperty location | Select-Object -ExpandProperty city # The city from where the sign-in occurred.
"State" = $Record | Select-Object -ExpandProperty location | Select-Object -ExpandProperty state # The state from where the sign-in occurred.
"CountryOrRegion" = $Record | Select-Object -ExpandProperty location | Select-Object -ExpandProperty countryOrRegion # The two letter country code from where the sign-in occurred.
"Latitude" = $Record | Select-Object -ExpandProperty location | Select-Object -ExpandProperty geoCoordinates | Select-Object -ExpandProperty Latitude # The latitude, in decimal, for the item.
"Longitude" = $Record | Select-Object -ExpandProperty location | Select-Object -ExpandProperty geoCoordinates | Select-Object -ExpandProperty Longitude # The longitude, in decimal, for the item.
"AuthenticationRequirement" = $Record.AuthenticationRequirement # This holds the highest level of authentication needed through all the sign-in steps, for sign-in to succeed.
"SignInEventTypes" = $Record | Select-Object -ExpandProperty SignInEventTypes # Indicates the category of sign in that the event represents.
"AuthenticationMethodsUsed" = $Record | Select-Object -ExpandProperty AuthenticationMethodsUsed # The authentication methods used.
# Status - The sign-in status. Includes the error code and description of the error (for a sign-in failure).
# https://learn.microsoft.com/nb-no/graph/api/resources/signinstatus?view=graph-rest-beta
"ErrorCode" = $Record | Select-Object -ExpandProperty status | Select-Object -ExpandProperty errorCode # Provides the 5-6 digit error code that's generated during a sign-in failure.
"FailureReason" = $Record | Select-Object -ExpandProperty status | Select-Object -ExpandProperty failureReason # Provides the error message or the reason for failure for the corresponding sign-in activity.
"AdditionalDetails" = $Record | Select-Object -ExpandProperty status | Select-Object -ExpandProperty additionalDetails # Provides additional details on the sign-in activity.
# AuthenticationDetails - The result of the authentication attempt and more details on the authentication method.
# https://learn.microsoft.com/nb-no/graph/api/resources/authenticationdetail?view=graph-rest-beta
"AuthenticationMethod" = $Record.AuthDetailsAuthenticationMethod # The type of authentication method used to perform this step of authentication.
"AuthenticationMethodDetail" = $Record.AuthDetailsAuthenticationMethodDetail # Details about the authentication method used to perform this authentication step.
"AuthenticationStepDateTime" = $Record.AuthDetailsAuthenticationStepDateTime # Represents date and time information using ISO 8601 format and is always in UTC time.
"AuthenticationStepRequirement" = $Record.AuthDetailsAuthenticationStepRequirement # The step of authentication that this satisfied.
"AuthenticationStepResultDetail" = $Record.AuthDetailsAuthenticationStepResultDetail # Details about why the step succeeded or failed.
"Succeeded" = $Record.AuthDetailsSucceeded # Indicates the status of the authentication step.
# AuthenticationProcessingDetails - More authentication processing details, such as the agent name for PTA and PHS, or a server or farm name for federated authentication.
"Domain Hint Present" = ($Record | Select-Object -ExpandProperty AuthenticationProcessingDetails | Where-Object {$_.Key -eq 'Domain Hint Present'}).Value
"Is CAE Token" = ($Record | Select-Object -ExpandProperty AuthenticationProcessingDetails | Where-Object {$_.Key -eq 'Is CAE Token'}).Value
"Login Hint Present" = ($Record | Select-Object -ExpandProperty AuthenticationProcessingDetails | Where-Object {$_.Key -eq 'Login Hint Present'}).Value
"Oauth Scope Info" = ($Record | Select-Object -ExpandProperty AuthenticationProcessingDetails | Where-Object {$_.Key -eq 'Oauth Scope Info'}).Value
"Root Key Type" = ($Record | Select-Object -ExpandProperty AuthenticationProcessingDetails | Where-Object {$_.Key -eq 'Root Key Type'}).Value
"ClientCredentialType" = $Record.ClientCredentialType # Describes the credential type that a user client or service principal provided to Microsoft Entra ID to authenticate itself. You can review this property to track and eliminate less secure credential types or to watch for clients and service principals using anomalous credential types.
"CredentialKeyId" = $Record.servicePrincipalCredentialKeyId # The unique identifier of the key credential used by the service principal to authenticate.
"CredentialThumbprint" = $Record.servicePrincipalCredentialThumbprint # The certificate thumbprint of the certificate used by the service principal to authenticate.
"ConditionalAccessStatus" = $Record.ConditionalAccessStatus # The status of the conditional access policy triggered.
"CorrelationId" = $Record.CorrelationId # The identifier that's sent from the client when sign-in is initiated.
"IncomingTokenType" = $Record.IncomingTokenType # Indicates the token types that were presented to Microsoft Entra ID to authenticate the actor in the sign in.
"OriginalRequestId" = $Record.OriginalRequestId # The request identifier of the first request in the authentication sequence.
"IsInteractive" = $Record.IsInteractive # Indicates whether a user sign in is interactive. In interactive sign in, the user provides an authentication factor to Microsoft Entra ID. These factors include passwords, responses to MFA challenges, biometric factors, or QR codes that a user provides to Microsoft Entra ID or an associated app. In non-interactive sign in, the user doesn't provide an authentication factor. Instead, the client app uses a token or code to authenticate or access a resource on behalf of a user. Non-interactive sign ins are commonly used for a client to sign in on a user's behalf in a process transparent to the user.
"ProcessingTimeInMilliseconds" = $Record.ProcessingTimeInMilliseconds # The request processing time in milliseconds in AD STS.
"ResourceDisplayName" = $Record.ResourceDisplayName # The name of the resource that the user signed in to.
"ResourceId" = $Record.ResourceId # The identifier of the resource that the user signed in to.
"ResourceServicePrincipalId" = $Record.ResourceServicePrincipalId # The identifier of the service principal representing the target resource in the sign-in event.
"ResourceTenantId" = $Record.ResourceTenantId # The tenant identifier of the resource referenced in the sign in.
"RiskDetail" = $Record.RiskDetail # The reason behind a specific state of a risky user, sign-in, or a risk event.
"RiskEventTypesV2" = $Record | Select-Object -ExpandProperty riskEventTypes_v2 # The list of risk event types associated with the sign-in. --> RiskEventTypesV2 (Old)
"RiskLevelAggregated" = $Record.RiskLevelAggregated # The aggregated risk level. The value hidden means the user or sign-in wasn't enabled for Microsoft Entra ID Protection.
"RiskLevelDuringSignIn" = $Record.RiskLevelDuringSignIn # The risk level during sign-in. The value hidden means the user or sign-in wasn't enabled for Microsoft Entra ID Protection.
"RiskState" = $Record.RiskState # The risk state of a risky user, sign-in, or a risk event.
"SignInTokenProtectionStatus" = $Record.SignInTokenProtectionStatus # Token protection creates a cryptographically secure tie between the token and the device it is issued to. This field indicates whether the signin token was bound to the device or not.
"TokenIssuerName" = $Record.TokenIssuerName # The name of the identity provider.
"TokenIssuerType" = $Record.TokenIssuerType # The type of identity provider.
"UniqueTokenIdentifier" = $Record.UniqueTokenIdentifier # A unique base64 encoded request identifier used to track tokens issued by Microsoft Entra ID as they're redeemed at resource providers.
"SessionId" = $Record.SessionId # Identifier of the session that was generated during the sign-in.
"UserType" = $Record | Select-Object -ExpandProperty UserType | ForEach-Object { $_.Replace("member","Member") } | ForEach-Object { $_.Replace("guest","Guest") } # Identifies whether the user is a member or guest in the tenant.
"AuthenticationProtocol" = $Record.AuthenticationProtocol # Lists the protocol type or grant type used in the authentication.
"OriginalTransferMethod" = $Record.OriginalTransferMethod # Transfer method used to initiate a session throughout all subsequent request.
"CrossTenantAccessType" = $Record.CrossTenantAccessType # Describes the type of cross-tenant access used by the actor to access the resource.
# MfaDetail - This property is deprecated.
"AuthMethod" = $Record | Select-Object -ExpandProperty MfaDetail | Select-Object -ExpandProperty AuthMethod
"AuthDetail" = $Record | Select-Object -ExpandProperty MfaDetail | Select-Object -ExpandProperty AuthDetail
# DeviceDetail - The device information from where the sign-in occurred. Includes information such as deviceId, OS, and browser.
# https://learn.microsoft.com/nb-no/graph/api/resources/devicedetail?view=graph-rest-beta
"DeviceId" = $Record | Select-Object -ExpandProperty DeviceDetail | Select-Object -ExpandProperty DeviceId # Refers to the UniqueID of the device used for signing-in.
"DisplayName" = $Record | Select-Object -ExpandProperty DeviceDetail | Select-Object -ExpandProperty DisplayName # Refers to the name of the device used for signing-in.
"OperatingSystem" = $Record | Select-Object -ExpandProperty DeviceDetail | Select-Object -ExpandProperty OperatingSystem # Indicates the OS name and version used for signing-in.
"Browser" = $Record | Select-Object -ExpandProperty DeviceDetail | Select-Object -ExpandProperty Browser # Indicates the browser information of the used for signing-in.
"IsCompliant" = $Record | Select-Object -ExpandProperty DeviceDetail | Select-Object -ExpandProperty IsCompliant # Indicates whether the device is compliant or not.
"IsManaged" = $Record | Select-Object -ExpandProperty DeviceDetail | Select-Object -ExpandProperty IsManaged # Indicates if the device is managed or not.
"TrustType" = $Record | Select-Object -ExpandProperty DeviceDetail | Select-Object -ExpandProperty TrustType # Indicates information on whether the signed-in device is Workplace Joined, AzureAD Joined, Domain Joined.
# NetworkLocationDetails - The network location details including the type of network used and its names.
# https://learn.microsoft.com/nb-no/graph/api/resources/networklocationdetail?view=graph-rest-beta
"NetworkType" = $NetworkType # Provides the type of network used when signing in.
"NetworkNames" = $NetworkNames # Provides the name of the network used when signing in.
"TrustedNamedLocation" = $TrustedNamedLocation
# Agent - Represents details about the agentic sign-in.
# https://learn.microsoft.com/nb-no/graph/api/resources/agentic-agentsignin?view=graph-rest-beta
"AgentType" = $Record | Select-Object -ExpandProperty agent | Select-Object -ExpandProperty agentType # The type of agent for agentic sign-ins.
"ParentAppId" = $Record | Select-Object -ExpandProperty agent | Select-Object -ExpandProperty parentAppId # The ID of the parent application for agentic instances.
# IsAgent
# notAgentic --> No
# agenticAppBuilder --> Yes
# agenticApp --> Yes
# agenticAppInstance --> Yes
# unknownFutureValue --> No
}
$Results.Add($Line)
}
$Results | Export-Csv -Path "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\CSV\Untouched.csv" -NoTypeInformation -Encoding UTF8
# XLSX
$Results | Export-Excel -Path "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\XLSX\Untouched.xlsx" -NoNumberConversion * -NoHyperLinkConversion * -FreezePane 2,5 -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "SignInLogsGraph" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
Set-Format -Address $WorkSheet.Cells["A1:BW1"] -BackgroundColor $BackgroundColor -FontColor $FontColor
# HorizontalAlignment "Center" of columns A-BW
$WorkSheet.Cells["A:BW"].Style.HorizontalAlignment="Center"
}
# Microsoft Entra Workload ID Premium
# https://learn.microsoft.com/en-us/entra/id-protection/concept-workload-identity-risk
$RiskLevelDuringSignIn = (Import-Csv -Path "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\CSV\Untouched.csv" -Delimiter "," | Select-Object RiskLevelDuringSignIn -Unique).RiskLevelDuringSignIn
if ("$RiskLevelDuringSignIn" -eq "hidden")
{
Write-Host "[Info] No Microsoft Entra Workload ID Premium detected" -ForegroundColor Red
}
else
{
Write-Host "[Info] Microsoft Entra Workload ID Premium detected" -ForegroundColor Green
}
$EndTime_Processing = (Get-Date)
$Time_Processing = ($EndTime_Processing-$StartTime_Processing)
('ServicePrincipalSignInLogs Processing duration: {0} h {1} min {2} sec' -f $Time_Processing.Hours, $Time_Processing.Minutes, $Time_Processing.Seconds) >> "$OUTPUT_FOLDER\Stats.txt"
}
#############################################################################################################################################################################################
#############################################################################################################################################################################################
Function Get-IPLocation {
$StartTime_DataEnrichment = (Get-Date)
# Count IP addresses
Write-Output "[Info] Data Enrichment w/ IPinfo ..."
New-Item "$OUTPUT_FOLDER\IPAddress" -ItemType Directory -Force | Out-Null
$Data = Import-Csv -Path "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\CSV\Untouched.csv" -Delimiter "," | Select-Object -ExpandProperty IpAddress
$Unique = $Data | Sort-Object -Unique
$Unique | Out-File "$OUTPUT_FOLDER\IPAddress\IP-All.txt" -Encoding UTF8
$Count = ($Unique | Measure-Object).Count
$UniqueIP = '{0:N0}' -f $Count
$Total = ($Data | Measure-Object).Count
Write-Output "[Info] $UniqueIP IP addresses found ($Total)"
# IPv4
# https://ipinfo.io/bogon
$IPv4 = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
$Private = "^(192\.168|10\.|172\.1[6789]\.|172\.2[0-9]\.|172\.3[01]\.)"
$Special = "^(0\.0\.0\.0|127\.0\.0\.1|169\.254\.|224\.0\.0)"
Get-Content "$OUTPUT_FOLDER\IPAddress\IP-All.txt" | Select-String -Pattern $IPv4 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique -Property { [System.Version]$_ } | Out-File "$OUTPUT_FOLDER\IPAddress\IPv4-All.txt" -Encoding UTF8
Get-Content "$OUTPUT_FOLDER\IPAddress\IP-All.txt" | Select-String -Pattern $IPv4 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique -Property { [System.Version]$_ } | Where-Object {$_ -notmatch $Private} | Where-Object {$_ -notmatch $Special} | Out-File "$OUTPUT_FOLDER\IPAddress\IPv4.txt" -Encoding UTF8
# Count
$Total = (Get-Content "$OUTPUT_FOLDER\IPAddress\IPv4-All.txt" | Measure-Object).Count # Public (Unique) + Private (Unique) --> Note: Extracts IPv4 addresses of IPv4-compatible IPv6 addresses.
$Public = (Get-Content "$OUTPUT_FOLDER\IPAddress\IPv4.txt" | Measure-Object).Count # Public (Unique)
$UniquePublic = '{0:N0}' -f $Public
Write-Output "[Info] $UniquePublic Public IPv4 addresses found ($Total)"
# IPv6
# https://ipinfo.io/bogon
$IPv6 = ":(?::[a-f\d]{1,4}){0,5}(?:(?::[a-f\d]{1,4}){1,2}|:(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})))|[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}:(?:[a-f\d]{1,4}|:)|(?::(?:[a-f\d]{1,4})?|(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))))|:(?:(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|[a-f\d]{1,4}(?::[a-f\d]{1,4})?|))|(?::(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|:[a-f\d]{1,4}(?::(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[a-f\d]{1,4}){0,2})|:))|(?:(?::[a-f\d]{1,4}){0,2}(?::(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[a-f\d]{1,4}){1,2})|:))|(?:(?::[a-f\d]{1,4}){0,3}(?::(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[a-f\d]{1,4}){1,2})|:))|(?:(?::[a-f\d]{1,4}){0,4}(?::(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[a-f\d]{1,4}){1,2})|:))"
$Bogon = "^(::1|::ffff:|100::|2001:10::|2001:db8::|fc00::|fd00::|fe80::|fec0::|ff00::)"
Get-Content "$OUTPUT_FOLDER\IPAddress\IP-All.txt" | Select-String -Pattern $IPv6 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique | Out-File "$OUTPUT_FOLDER\IPAddress\IPv6-All.txt" -Encoding UTF8
Get-Content "$OUTPUT_FOLDER\IPAddress\IP-All.txt" | Select-String -Pattern $IPv6 -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value } | Sort-Object -Unique | Where-Object {$_ -notmatch $Bogon} | Out-File "$OUTPUT_FOLDER\IPAddress\IPv6.txt" -Encoding UTF8
# Count
$Total = (Get-Content "$OUTPUT_FOLDER\IPAddress\IPv6-All.txt" | Measure-Object).Count # including Bogus IPv6 addresses (e.g. IPv4-compatible IPv6 addresses)
$Public = (Get-Content "$OUTPUT_FOLDER\IPAddress\IPv6.txt" | Measure-Object).Count
Write-Output "[Info] $Public Public IPv6 addresses found ($Total)"
# IP.txt
Write-Output "IPAddress" | Out-File "$OUTPUT_FOLDER\IPAddress\IP.txt" -Encoding UTF8 # Header
# IPv4.txt
if (Test-Path "$OUTPUT_FOLDER\IPAddress\IPv4.txt")
{
if ((Get-Item "$OUTPUT_FOLDER\IPAddress\IPv4.txt").Length -gt 0kb)
{
Get-Content -Path "$OUTPUT_FOLDER\IPAddress\IPv4.txt" | Out-File "$OUTPUT_FOLDER\IPAddress\IP.txt" -Encoding UTF8 -Append
}
}
# IPv6.txt
if (Test-Path "$OUTPUT_FOLDER\IPAddress\IPv6.txt")
{
if ((Get-Item "$OUTPUT_FOLDER\IPAddress\IPv6.txt").Length -gt 0kb)
{
Get-Content -Path "$OUTPUT_FOLDER\IPAddress\IPv6.txt" | Out-File "$OUTPUT_FOLDER\IPAddress\IP.txt" -Encoding UTF8 -Append
}
}
# Check IPinfo Subscription Plan (https://ipinfo.io/pricing)
if (Test-Path "$($IPinfo)")
{
$Quota = & $IPinfo quota
if ($Quota -eq "err: please login first to check quota")
{
# IPinfo Login
& $IPinfo init "$Token" > $null
$Quota = & $IPinfo quota
}
Write-Output "[Info] Checking IPinfo Subscription Plan ..."
[int]$TotalRequests = $Quota | Select-String -Pattern "Total Requests" | ForEach-Object{($_ -split "\s+")[-1]}
[int]$RemainingRequests = $Quota | Select-String -Pattern "Remaining Requests" | ForEach-Object{($_ -split "\s+")[-1]}
$TotalMonth = '{0:N0}' -f $TotalRequests | ForEach-Object {$_ -replace ' ','.'}
$RemainingMonth = '{0:N0}' -f $RemainingRequests | ForEach-Object {$_ -replace ' ','.'}
if (& $IPinfo myip --token "$Token" | Select-String -Pattern "Privacy" -Quiet)
{
$script:PrivacyDetection = "True"
Write-output "[Info] IPinfo Subscription Plan w/ Privacy Detection found"
Write-Output "[Info] $RemainingMonth Requests left this month"
}
else
{
$script:PrivacyDetection = "False"
Write-output "[Info] IPinfo Subscription: Free ($TotalMonth Requests/Month)"
Write-Output "[Info] $RemainingMonth Requests left this month"
}
}
# IPinfo CLI
if (Test-Path "$($IPinfo)")
{
if (Test-Path "$OUTPUT_FOLDER\IPAddress\IP.txt")
{
if ((Get-Item "$OUTPUT_FOLDER\IPAddress\IP.txt").Length -gt 0kb)
{
# Internet Connectivity Check (Vista+)
$NetworkListManager = [Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet
if (!($NetworkListManager -eq "True"))
{
Write-Host "[Error] Your computer is NOT connected to the Internet. IP addresses cannot be checked via IPinfo API." -ForegroundColor Red
}
else
{
# Check if IPinfo.io is reachable
if (!(Test-NetConnection -ComputerName ipinfo.io -Port 443).TcpTestSucceeded)
{
Write-Host "[Error] ipinfo.io is NOT reachable. IP addresses cannot be checked via IPinfo API." -ForegroundColor Red
}
else
{
# Map IPs
# https://ipinfo.io/map
New-Item "$OUTPUT_FOLDER\IPAddress\IPinfo" -ItemType Directory -Force | Out-Null
Get-Content "$OUTPUT_FOLDER\IPAddress\IP.txt" | & $IPinfo map | Out-File "$OUTPUT_FOLDER\IPAddress\IPinfo\Map.txt" -Encoding UTF8
# Access Token
# https://ipinfo.io/signup?ref=cli
if (!("$Token" -eq "access_token"))
{
# Summarize IPs
# https://ipinfo.io/summarize-ips
# TXT --> Top Privacy Services
[int]$Count = (Get-Content "$OUTPUT_FOLDER\IPAddress\IP.txt" | Measure-Object).Count
if ($Count -ge 10)
{
Get-Content -Path "$OUTPUT_FOLDER\IPAddress\IP.txt" | & $IPinfo summarize --token "$Token" | Out-File "$OUTPUT_FOLDER\IPAddress\IPinfo\Summary.txt"
}
# CSV
Get-Content "$OUTPUT_FOLDER\IPAddress\IP.txt" | & $IPinfo --csv --token "$Token" | Out-File "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo.csv" -Encoding UTF8
# Custom CSV (Free)
if ($PrivacyDetection -eq "False")
{
if (Test-Path "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo.csv")
{
if(Test-Csv -Path "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo.csv" -MaxLines 2)
{
$IPinfoRecords = Import-Csv "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo.csv" -Delimiter "," -Encoding UTF8
$Results = [Collections.Generic.List[PSObject]]::new()
ForEach($IPinfoRecord in $IPinfoRecords)
{
$Line = [PSCustomObject]@{
"IP" = $IPinfoRecord.ip
"City" = $IPinfoRecord.city
"Region" = $IPinfoRecord.region
"Country" = $IPinfoRecord.country
"Country Name" = $IPinfoRecord.country_name
"EU" = $IPinfoRecord.isEU
"Location" = $IPinfoRecord.loc
"ASN" = $IPinfoRecord | Select-Object -ExpandProperty org | ForEach-Object{($_ -split "\s+")[0]}
"OrgName" = $IPinfoRecord | Select-Object -ExpandProperty org | ForEach-Object {$_ -replace "^AS[0-9]+ "}
"Postal Code" = $IPinfoRecord.postal
"Timezone" = $IPinfoRecord.timezone
}
$Results.Add($Line)
}
$Results | Sort-Object {$_.IP -as [Version]} | Export-Csv -Path "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo-Custom.csv" -NoTypeInformation -Encoding UTF8
}
}
# Custom XLSX (Free)
if (Test-Path "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo-Custom.csv")
{
if(Test-Csv -Path "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo-Custom.csv" -MaxLines 2)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo-Custom.csv" -Delimiter "," | Sort-Object {$_.ip -as [Version]}
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo-Custom.xlsx" -NoNumberConversion * -NoHyperLinkConversion * -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -IncludePivotTable -PivotTableName "PivotTable" -PivotRows "Country Name" -PivotData @{"IP"="Count"} -WorkSheetname "IPinfo (Free)" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
Set-Format -Address $WorkSheet.Cells["A1:K1"] -BackgroundColor $BackgroundColor -FontColor $FontColor
# HorizontalAlignment "Center" of columns A-K
$WorkSheet.Cells["A:K"].Style.HorizontalAlignment="Center"
}
}
}
}
# Create HashTable and import 'IPinfo-Custom.csv'
$script:IPinfo_HashTable = @{}
if (Test-Path "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo-Custom.csv")
{
if(Test-Csv -Path "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo-Custom.csv" -MaxLines 2)
{
# Free
if ($PrivacyDetection -eq "False")
{
Import-Csv -Path "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo-Custom.csv" -Delimiter "," -Encoding UTF8 | ForEach-Object { $IPinfo_HashTable[$_.IP] = $_.City,$_.Region,$_.Country,$_."Country Name",$_.Location,$_.ASN,$_.OrgName,$_."Postal Code",$_.Timezone }
}
# Count Ingested Properties
$Count = $IPinfo_HashTable.Count
Write-Output "[Info] Initializing 'IPinfo-Custom.csv' Lookup Table ($Count) ..."
}
}
# Create HashTable and import 'Status.csv'
$Status_HashTable = @{}
if (Test-Path "$SCRIPT_DIR\Config\Status.csv")
{
if(Test-Csv -Path "$SCRIPT_DIR\Config\Status.csv" -MaxLines 2)
{
Import-Csv "$SCRIPT_DIR\Config\Status.csv" -Delimiter "," -Encoding UTF8 | ForEach-Object { $Status_HashTable[$_.ErrorCode] = $_.Status, $_.Message }
}
}
else
{
Write-Output "Status.csv NOT found."
}
# Hunt
# IPinfo Subscription: Free
if ($PrivacyDetection -eq "False")
{
if (Test-Path "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\CSV\Untouched.csv")
{
if(Test-Csv -Path "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\CSV\Untouched.csv" -MaxLines 2)
{
$Records = Import-Csv -Path "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8
# CSV
$Results = [Collections.Generic.List[PSObject]]::new()
ForEach($Record in $Records)
{
# ApplicationType
if ($Record.AppOwnerTenantId -eq "72f988bf-86f1-41af-91ab-2d7cd011db47" -or $Record.AppOwnerTenantId -eq "f8cdef31-a31e-4b4a-93e4-5f571e91255a")
{
$ApplicationType = "First-Party Application" # Microsoft Application --> Traitorware?
}
else
{
$ApplicationType = "Third-Party Application" # Malware?
}
# Status
[int]$ErrorCode = $Record | Select-Object -ExpandProperty ErrorCode
# Check if HashTable contains IP
if($Status_HashTable.ContainsKey("$ErrorCode"))
{
$Status = $Status_HashTable["$ErrorCode"][0]
}
else
{
$Status = "Failure"
}
# Authorization Error Codes (AADSTS) aka Entra ID Sign-in Error Codes
# https://learn.microsoft.com/en-us/azure/active-directory/develop/reference-error-codes
# https://login.microsoftonline.com/error
# https://blog.icewolf.ch/archive/2021/02/04/hunting-for-basic-authentication-in-azuread/
# IpAddress
$IP = $Record.IpAddress
# Check if HashTable contains IP
if($IPinfo_HashTable.ContainsKey("$IP"))
{
$City = $IPinfo_HashTable["$IP"][0]
$Region = $IPinfo_HashTable["$IP"][1]
$Country = $IPinfo_HashTable["$IP"][2]
$CountryName = $IPinfo_HashTable["$IP"][3]
$Location = $IPinfo_HashTable["$IP"][4]
$ASN = $IPinfo_HashTable["$IP"][5] | ForEach-Object {$_ -replace "^AS"}
$OrgName = $IPinfo_HashTable["$IP"][6]
$PostalCode = $IPinfo_HashTable["$IP"][7]
$Timezone = $IPinfo_HashTable["$IP"][8]
}
else
{
$City = ""
$Region = ""
$Country = ""
$CountryName = ""
$Location = ""
$ASN = ""
$OrgName = ""
$PostalCode = ""
$Timezone = ""
}
$Line = [PSCustomObject]@{
"Id" = $Record.Id
"CreatedDateTime" = $Record.CreatedDateTime
"AppId" = $Record.AppId
"AppDisplayName" = $Record.AppDisplayName
"AppOwnerTenantId" = $Record.AppOwnerTenantId
"ApplicationType" = $ApplicationType
"ResourceOwnerTenantId" = $Record.ResourceOwnerTenantId
"ServicePrincipalId" = $Record.ServicePrincipalId
"ServicePrincipalName" = $Record.ServicePrincipalName
"ClientCredentialType" = $Record.ClientCredentialType
"CredentialKeyId" = $Record.CredentialKeyId
"CredentialThumbprint" = $Record.CredentialThumbprint
"ConditionalAccessStatus" = $Record.ConditionalAccessStatus
"OriginalRequestId" = $Record.OriginalRequestId
"SignInEventType" = $Record.SignInEventTypes
"TokenIssuerName" = $Record.TokenIssuerName
"TokenIssuerType" = $Record.TokenIssuerType
"ProcessingTimeInMilliseconds" = $Record.ProcessingTimeInMilliseconds
"RiskLevelAggregated" = $Record.RiskLevelAggregated
"RiskLevelDuringSignIn" = $Record.RiskLevelDuringSignIn
"RiskState" = $Record.RiskState
"RiskDetail" = $Record.RiskDetail
"RiskEventTypesV2" = $Record.RiskEventTypesV2
"ResourceDisplayName" = $Record.ResourceDisplayName
"ResourceId" = $Record.ResourceId
"AuthenticationMethodsUsed" = $Record.AuthenticationMethodsUsed
"ErrorCode" = $Record.ErrorCode
"FailureReason" = $Record.FailureReason
"AdditionalDetails" = $Record.AdditionalDetails
"Status" = $Status
"DeviceId" = $Record.DeviceId
"DisplayName" = $Record.DisplayName
"OperatingSystem" = $Record.OperatingSystem
"Browser" = $Record.Browser
"IsCompliant" = $Record.IsCompliant
"IsManaged" = $Record.IsManaged
"TrustType" = $Record.TrustType
"AuthMethod" = $Record.AuthMethod
"AuthDetail" = $Record.AuthDetail
"AuthenticationProtocol" = $Record.AuthenticationProtocol
"OriginalTransferMethod" = $Record.OriginalTransferMethod
"IPAddress" = $IP
"City" = $City
"Region" = $Region
"Country" = $Country
"Country Name" = $CountryName
"Location" = $Location
"ASN" = $ASN
"OrgName" = $OrgName
"Postal Code" = $PostalCode
"Timezone" = $Timezone
"UserAgent" = $Record.UserAgent
"TrustedNamedLocation" = $Record.TrustedNamedLocation
"UniqueTokenIdentifier" = $Record.UniqueTokenIdentifier
"SessionId" = $Record.SessionId
"CorrelationId" = $Record.CorrelationId
"IncomingTokenType" = $Record.IncomingTokenType
"SignInTokenProtectionStatus" = $Record.SignInTokenProtectionStatus
"CrossTenantAccessType" = $Record.CrossTenantAccessType
"AgentType" = $Record.AgentType
"ParentAppId" = $Record.ParentAppId
}
$Results.Add($Line)
}
$Results | Sort-Object {$_.IP -as [Version]} | Export-Csv -Path "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\CSV\Hunt.csv" -NoTypeInformation -Encoding UTF8
}
}
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\CSV\Hunt.csv")
{
if(Test-Csv -Path "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\CSV\Hunt.csv" -MaxLines 2)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ServicePrincipalSignInLogs\CSV\Hunt.csv" -Delimiter "," | Sort-Object { $_.CreatedDateTime -as [datetime] } -Descending
# 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
}
# Common Naming Patterns of Malicious OAuth Applications
[array]$RegEx02 = $Import | Where-Object { $_.AppDisplayName -match "^(test|test app|app test|apptest)$" } | Select-Object -ExpandProperty AppDisplayName
$Count = ($RegEx02 | Select-Object AppId -Unique | Measure-Object).Count
if ($Count -gt 0)