-
Notifications
You must be signed in to change notification settings - Fork 43
/
ADAuditLogsGraph-Analyzer.ps1
2304 lines (2037 loc) · 165 KB
/
ADAuditLogsGraph-Analyzer.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ADAuditLogsGraph-Analyzer
#
# @author: Martin Willing
# @copyright: Copyright (c) 2024 Martin Willing. All rights reserved. Licensed under the MIT license.
# @contact: Any feedback or suggestions are always welcome and much appreciated - [email protected]
# @url: https://lethal-forensics.com/
# @date: 2024-12-17
#
#
# ██╗ ███████╗████████╗██╗ ██╗ █████╗ ██╗ ███████╗ ██████╗ ██████╗ ███████╗███╗ ██╗███████╗██╗ ██████╗███████╗
# ██║ ██╔════╝╚══██╔══╝██║ ██║██╔══██╗██║ ██╔════╝██╔═══██╗██╔══██╗██╔════╝████╗ ██║██╔════╝██║██╔════╝██╔════╝
# ██║ █████╗ ██║ ███████║███████║██║█████╗█████╗ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║███████╗██║██║ ███████╗
# ██║ ██╔══╝ ██║ ██╔══██║██╔══██║██║╚════╝██╔══╝ ██║ ██║██╔══██╗██╔══╝ ██║╚██╗██║╚════██║██║██║ ╚════██║
# ███████╗███████╗ ██║ ██║ ██║██║ ██║███████╗ ██║ ╚██████╔╝██║ ██║███████╗██║ ╚████║███████║██║╚██████╗███████║
# ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═════╝╚══════╝
#
#
# 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
#
# xsv v0.13.0 (2018-05-12)
# https://github.com/BurntSushi/xsv
#
#
# Tested on Windows 10 Pro (x64) Version 22H2 (10.0.19045.5247) and PowerShell 5.1 (5.1.19041.5247)
# Tested on Windows 10 Pro (x64) Version 22H2 (10.0.19045.5247) and PowerShell 7.4.6
#
#
#############################################################################################################################################################################################
#############################################################################################################################################################################################
<#
.SYNOPSIS
ADAuditLogsGraph-Analyzer - Automated Processing of Microsoft Entra ID Audit Logs for DFIR
.DESCRIPTION
ADAuditLogsGraph-Analyzer.ps1 is a PowerShell script utilized to simplify the analysis of Microsoft Entra ID Audit Logs extracted via "Microsoft Extractor Suite" by Invictus-IR.
https://github.com/invictus-ir/Microsoft-Extractor-Suite (Microsoft-Extractor-Suite v2.1.1)
https://microsoft-365-extractor-suite.readthedocs.io/en/latest/functionality/AzureAuditLogsGraph.html
.PARAMETER OutputDir
Specifies the output directory. Default is "$env:USERPROFILE\Desktop\ADAuditLogsGraph-Analyzer".
Note: The subdirectory 'ADAuditLogsGraph-Analyzer' is automatically created.
.PARAMETER Path
Specifies the path to the JSON-based input file (AuditLogs-Combined.json).
.EXAMPLE
PS> .\ADAuditLogsGraph-Analyzer.ps1
.EXAMPLE
PS> .\ADAuditLogsGraph-Analyzer.ps1 -Path "$env:USERPROFILE\Desktop\AuditLogs-Combined.json"
.EXAMPLE
PS> .\ADAuditLogsGraph-Analyzer.ps1 -Path "H:\Microsoft-Extractor-Suite\AuditLogs-Combined.json" -OutputDir "H:\Microsoft-Analyzer-Suite"
.NOTES
Author - Martin Willing
.LINK
https://lethal-forensics.com/
#>
#############################################################################################################################################################################################
#############################################################################################################################################################################################
# How long does Microsoft Entra ID store the Audit logs data?
# Microsoft Entra ID Free 7 days
# Microsoft Entra ID P1 30 days
# Microsoft Entra ID P2 30 days
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#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
}
# Custom Colors
Add-Type -AssemblyName System.Drawing
$script:Green = [System.Drawing.Color]::FromArgb(0,176,80) # Green
$script:Orange = [System.Drawing.Color]::FromArgb(255,192,0) # Orange
# Output Directory
if (!($OutputDir))
{
$script:OUTPUT_FOLDER = "$env:USERPROFILE\Desktop\ADAuditLogsGraph-Analyzer" # Default
}
else
{
if ($OutputDir -cnotmatch '.+(?=\\)')
{
Write-Host "[Error] You must provide a valid directory path." -ForegroundColor Red
Exit
}
else
{
$script:OUTPUT_FOLDER = "$OutputDir\ADAuditLogsGraph-Analyzer" # Custom
}
}
# Tools
# IPinfo CLI
$script:IPinfo = "$SCRIPT_DIR\Tools\IPinfo\ipinfo.exe"
# xsv
$script:xsv = "$SCRIPT_DIR\Tools\xsv\xsv.exe"
# Configuration File
if(!(Test-Path "$PSScriptRoot\Config.ps1"))
{
Write-Host "[Error] Config.ps1 NOT found." -ForegroundColor Red
}
else
{
. "$PSScriptRoot\Config.ps1"
}
#endregion Declarations
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region Header
# Windows Title
$DefaultWindowsTitle = $Host.UI.RawUI.WindowTitle
$Host.UI.RawUI.WindowTitle = "ADAuditLogsGraph-Analyzer - Automated Processing of Microsoft Entra ID Audit Logs for DFIR"
# 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
}
# 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-FileSize
Function Get-FileSize()
{
Param ([long]$Length)
If ($Length -gt 1TB) {[string]::Format("{0:0.00} TB", $Length / 1TB)}
ElseIf ($Length -gt 1GB) {[string]::Format("{0:0.00} GB", $Length / 1GB)}
ElseIf ($Length -gt 1MB) {[string]::Format("{0:0.00} MB", $Length / 1MB)}
ElseIf ($Length -gt 1KB) {[string]::Format("{0:0.00} KB", $Length / 1KB)}
ElseIf ($Length -gt 0) {[string]::Format("{0:0.00} Bytes", $Length)}
Else {""}
}
# 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 = "Entra ID Audit Logs|AuditLogs-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 "ADAuditLogsGraph-Analyzer - Automated Processing of Microsoft Entra ID Audit Logs for DFIR"
Write-Output "(c) 2024 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([int](& $xsv count "$SCRIPT_DIR\Blacklists\Application-Blacklist.csv") -gt 0)
{
Import-Csv "$SCRIPT_DIR\Blacklists\Application-Blacklist.csv" -Delimiter "," | ForEach-Object { $ApplicationBlacklist_HashTable[$_.AppId] = $_.AppDisplayName,$_.Severity }
}
}
# Create HashTable and import 'ASN-Blacklist.csv'
$script:AsnBlacklist_HashTable = [ordered]@{}
if (Test-Path "$SCRIPT_DIR\Blacklists\ASN-Blacklist.csv")
{
if([int](& $xsv count "$SCRIPT_DIR\Blacklists\ASN-Blacklist.csv") -gt 0)
{
Import-Csv "$SCRIPT_DIR\Blacklists\ASN-Blacklist.csv" -Delimiter "," | ForEach-Object { $AsnBlacklist_HashTable[$_.ASN] = $_.OrgName,$_.Info }
}
}
# Create HashTable and import 'Country-Blacklist.csv'
$script:CountryBlacklist_HashTable = [ordered]@{}
if (Test-Path "$SCRIPT_DIR\Blacklists\Country-Blacklist.csv")
{
if([int](& $xsv count "$SCRIPT_DIR\Blacklists\Country-Blacklist.csv") -gt 0)
{
Import-Csv "$SCRIPT_DIR\Blacklists\Country-Blacklist.csv" -Delimiter "," | ForEach-Object { $CountryBlacklist_HashTable[$_."Country Name"] = $_.Country }
}
}
#endregion Header
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region Analysis
# Microsoft Entra ID Audit Logs (Last 7 days / Last 30 days)
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
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.ps1'" -ForegroundColor Red
Write-Host ""
Stop-Transcript
$Host.UI.RawUI.WindowTitle = "$DefaultWindowsTitle"
Exit
}
# Import JSON
Write-Output "[Info] Importing JSON data ..."
$Data = (Get-Content -Path "$LogFile" -Raw) -join "`n`r" | ConvertFrom-Json | Sort-Object { $_.activityDateTime -as [datetime] } -Descending # UTF-8 with BOM
# UserId
$UserIds = ($Data | Select-Object -ExpandProperty InitiatedBy | Select-Object -ExpandProperty User | Select-Object -ExpandProperty Id | Sort-Object -Unique).Count
if ($Count -eq 1)
{
$UserId = ($UserIds).UserIds
$Message = "[Info] Processing Microsoft Entra ID Audit Logs ($UserId) ..."
}
else
{
$Message = "[Info] Processing Microsoft Entra ID Audit Logs [time-consuming task] ..."
}
# 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"
# Time Frame
$Last = ($Data | Sort-Object { $_.activityDateTime -as [datetime] } -Descending | Select-Object -Last 1).activityDateTime
$First = ($Data | Sort-Object { $_.activityDateTime -as [datetime] } -Descending | Select-Object -First 1).activityDateTime
$StartDate = (Get-Date $Last).ToString("yyyy-MM-dd HH:mm:ss")
$EndDate = (Get-Date $First).ToString("yyyy-MM-dd HH:mm:ss")
Write-Output "[Info] Log data from $StartDate UTC until $EndDate UTC"
# Processing Microsoft Entra ID Audit Log
Write-Output "$Message"
New-Item "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV" -ItemType Directory -Force | Out-Null
New-Item "$OUTPUT_FOLDER\ADAuditLogsGraph\XLSX" -ItemType Directory -Force | Out-Null
# Untouched
# https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.reports/get-mgauditlogdirectoryaudit?view=graph-powershell-1.0
# https://learn.microsoft.com/en-us/graph/api/resources/directoryaudit?view=graph-rest-1.0
# https://learn.microsoft.com/en-us/entra/identity/monitoring-health/reference-audit-activities
# CSV
$Results = [Collections.Generic.List[PSObject]]::new()
ForEach($Record in $Data)
{
$ActorObjectId = $Record | Select-Object -ExpandProperty initiatedBy | Select-Object -ExpandProperty user | Select-Object -ExpandProperty id
if ($null -eq $ActorObjectId)
{
$ActorType = "App"
}
else
{
$ActorType = "User"
}
$ActivityDateTime = $Record | Select-Object -ExpandProperty activityDateTime
$Line = [PSCustomObject]@{
"ActivityDateTime" = (Get-Date $ActivityDateTime).ToString("yyyy-MM-dd HH:mm:ss.fff") # Indicates the date and time the activity was performed. The Timestamp type is always in UTC time.
"InitiatedBy (UPN)" = ($Record | Select-Object -ExpandProperty initiatedBy | Select-Object -ExpandProperty $ActorType | Select-Object userPrincipalName).userPrincipalName # The userPrincipalName attribute of the user.
"TargetResources (UPN)" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object userPrincipalName | Select-Object -Index 0).userPrincipalName # When type is set to User, this includes the user name that initiated the action; null for other types.
"UserId" = ($Record | Select-Object -ExpandProperty initiatedBy | Select-Object -ExpandProperty $ActorType | Select-Object id).id # Unique identifier for the identity.
"AppDisplayName" = ($Record | Select-Object -ExpandProperty initiatedBy | Select-Object -ExpandProperty $ActorType | Select-Object displayName).displayName # Refers to the application name displayed in the Microsoft Entra admin center.
"AppId" = ($Record | Select-Object -ExpandProperty initiatedBy | Select-Object -ExpandProperty $ActorType | Select-Object appId).appId # Refers to the unique ID representing application in Microsoft Entra ID.
"ServicePrincipalId" = ($Record | Select-Object -ExpandProperty initiatedBy | Select-Object -ExpandProperty $ActorType | Select-Object servicePrincipalId).servicePrincipalId # Refers to the unique ID for the service principal in Microsoft Entra ID.
"LoggedByService" = $Record.loggedByService # Indicates information on which service initiated the activity.
"Category" = $Record.category # Indicates which resource category that's targeted by the activity.
"ActivityDisplayName" = $Record.activityDisplayName # Indicates the activity name or the operation name.
"OperationType" = $Record.operationType # Indicates the type of operation that was performed.
"Result" = $Record.result # Indicates the result of the activity.
"ResultReason" = $Record.resultReason # Indicates the reason for failure if the result is failure or timeout.
"IPAddress" = ($Record | Select-Object -ExpandProperty initiatedBy | Select-Object -ExpandProperty $ActorType | Select-Object iPAddress).iPAddress # Indicates the client IP address used by user performing the activity.
# InitiatedBy - Indicates information about the user or app initiated the activity.
# https://learn.microsoft.com/en-us/graph/api/resources/useridentity?view=graph-rest-1.0
# https://learn.microsoft.com/en-us/graph/api/resources/appidentity?view=graph-rest-1.0
"UserDisplayName" = ($Record | Select-Object -ExpandProperty initiatedBy | Select-Object -ExpandProperty $ActorType | Select-Object displayName).displayName # The identity's display name. This may not always be available or up-to-date.
"ServicePrincipalName" = ($Record | Select-Object -ExpandProperty initiatedBy | Select-Object -ExpandProperty $ActorType | Select-Object servicePrincipalName).servicePrincipalName # Refers to the Service Principal Name is the Application name in the tenant.
# TargetResources
# https://learn.microsoft.com/en-us/graph/api/resources/targetresource?view=graph-rest-1.0
# https://learn.microsoft.com/en-us/graph/api/resources/modifiedproperty?view=graph-rest-1.0
"Target1DisplayName" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object displayName | Select-Object -Index 0).displayName # Indicates the visible name defined for the resource.
"Target1GroupType" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object groupType | Select-Object -Index 0).groupType # When type is set to Group, this indicates the group type.
"Target1Id" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object id | Select-Object -Index 0).id # Indicates the unique ID of the resource.
"Target1Type" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object type | Select-Object -Index 0).type # Describes the resource type.
"Target1ModifiedProperty1Name" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object displayName | Select-Object -Index 0).displayName # Indicates the property name of the target attribute that was changed.
"Target1ModifiedProperty1OldValue" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object oldValue | Select-Object -Index 0).oldValue | ForEach-Object {$_ -replace '"',''} | ForEach-Object {$_ -replace '[[\]]',''} # Indicates the previous value (before the update) for the property.
"Target1ModifiedProperty1NewValue" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object newValue | Select-Object -Index 0).newValue | ForEach-Object {$_ -replace '"',''} | ForEach-Object {$_ -replace '[[\]]',''} # Indicates the updated value for the propery.
"Target1ModifiedProperty2Name" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object displayName | Select-Object -Index 1).displayName # Indicates the property name of the target attribute that was changed.
"Target1ModifiedProperty2OldValue" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object oldValue | Select-Object -Index 1).oldValue | ForEach-Object {$_ -replace '"',''} | ForEach-Object {$_ -replace '[[\]]',''} # Indicates the previous value (before the update) for the property.
"Target1ModifiedProperty2NewValue" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object newValue | Select-Object -Index 1).newValue | ForEach-Object {$_ -replace '"',''} | ForEach-Object {$_ -replace '[[\]]',''} # Indicates the updated value for the propery.
"Target1ModifiedProperty3Name" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object displayName | Select-Object -Index 2).displayName # Indicates the property name of the target attribute that was changed.
"Target1ModifiedProperty3OldValue" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object oldValue | Select-Object -Index 2).oldValue | ForEach-Object {$_ -replace '"',''} | ForEach-Object {$_ -replace '[[\]]',''} # Indicates the previous value (before the update) for the property.
"Target1ModifiedProperty3NewValue" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object newValue | Select-Object -Index 2).newValue | ForEach-Object {$_ -replace '"',''} | ForEach-Object {$_ -replace '[[\]]',''} # Indicates the updated value for the propery.
"Target1ModifiedProperty4Name" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object displayName | Select-Object -Index 3).displayName # Indicates the property name of the target attribute that was changed.
"Target1ModifiedProperty4OldValue" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object oldValue | Select-Object -Index 3).oldValue | ForEach-Object {$_ -replace '"',''} | ForEach-Object {$_ -replace '[[\]]',''} # Indicates the previous value (before the update) for the property.
"Target1ModifiedProperty4NewValue" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object newValue | Select-Object -Index 3).newValue | ForEach-Object {$_ -replace '"',''} | ForEach-Object {$_ -replace '[[\]]',''} # Indicates the updated value for the propery.
"Target1ModifiedProperty5Name" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object displayName | Select-Object -Index 4).displayName # Indicates the property name of the target attribute that was changed.
"Target1ModifiedProperty5OldValue" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object oldValue | Select-Object -Index 4).oldValue | ForEach-Object {$_ -replace '"',''} | ForEach-Object {$_ -replace '[[\]]',''} # Indicates the previous value (before the update) for the property.
"Target1ModifiedProperty5NewValue" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object -ExpandProperty modifiedProperties | Select-Object newValue | Select-Object -Index 4).newValue | ForEach-Object {$_ -replace '"',''} | ForEach-Object {$_ -replace '[[\]]',''} # Indicates the updated value for the propery.
"Target1UserPrincipalName" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object userPrincipalName | Select-Object -Index 0).userPrincipalName # When type is set to User, this includes the user name that initiated the action; null for other types.
"Target2DisplayName" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object displayName | Select-Object -Index 1).displayName
"Target2GroupType" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object groupType | Select-Object -Index 1).groupType
"Target2Id" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object id | Select-Object -Index 1).id
"Target2Type" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object type | Select-Object -Index 1).type
"Target2UserPrincipalName" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object userPrincipalName | Select-Object -Index 1).userPrincipalName
"Target3DisplayName" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object displayName | Select-Object -Index 2).displayName
"Target3GroupType" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object groupType | Select-Object -Index 2).groupType
"Target3Id" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object id | Select-Object -Index 2).id
"Target3Type" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object type | Select-Object -Index 2).type
"Target3UserPrincipalName" = ($Record | Select-Object -ExpandProperty targetResources | Select-Object userPrincipalName | Select-Object -Index 2).userPrincipalName
# AdditionalDetails
"GroupType" = ($Record | Select-Object -ExpandProperty additionalDetails | Where-Object {$_.Key -eq 'GroupType'}).Value # Unified
"UserType" = ($Record | Select-Object -ExpandProperty additionalDetails | Where-Object {$_.Key -eq 'UserType'}).Value # Guest, Member
"UserAgent" = ($Record | Select-Object -ExpandProperty additionalDetails | Where-Object {$_.Key -eq 'User-Agent'}).Value
"DeviceId" = ($Record | Select-Object -ExpandProperty additionalDetails | Where-Object {$_.Key -eq 'DeviceId'}).Value
"DeviceOSType" = ($Record | Select-Object -ExpandProperty additionalDetails | Where-Object {$_.Key -eq 'DeviceOSType'}).Value
"DeviceTrustType" = ($Record | Select-Object -ExpandProperty additionalDetails | Where-Object {$_.Key -eq 'DeviceTrustType'}).Value
"CorrelationId" = $Record.correlationId # Indicates a unique ID that helps correlate activities that span across various services. Can be used to trace logs across services.
"Id" = $Record.id # Indicates the unique ID for the activity.
}
$Results.Add($Line)
}
$Results | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Get-Module -ListAvailable -Name ImportExcel)
{
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\XLSX\Untouched.xlsx" -NoNumberConversion * -NoHyperLinkConversion * -FreezePane 2,4 -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "ADAuditLogsGraph" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:BB1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A-L, N-U and X-BB
$WorkSheet.Cells["A:L"].Style.HorizontalAlignment="Center"
$WorkSheet.Cells["N:U"].Style.HorizontalAlignment="Center"
$WorkSheet.Cells["X:BB"].Style.HorizontalAlignment="Center"
}
}
}
}
# File Size (Untouched.xlsx)
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\XLSX\Untouched.xlsx")
{
$Size = Get-FileSize((Get-Item "$OUTPUT_FOLDER\ADAuditLogsGraph\XLSX\Untouched.xlsx").Length)
Write-Output "[Info] File Size (Untouched.xlsx): $Size"
}
$EndTime_Processing = (Get-Date)
$Time_Processing = ($EndTime_Processing-$StartTime_Processing)
('ADAuditLogsGraph Processing duration: {0} h {1} min {2} sec' -f $Time_Processing.Hours, $Time_Processing.Minutes, $Time_Processing.Seconds) >> "$OUTPUT_FOLDER\Stats.txt"
}
Start-Processing
#############################################################################################################################################################################################
#############################################################################################################################################################################################
#region Stats
Function Get-Stats {
$StartTime_Stats = (Get-Date)
# Stats
Write-Output "[Info] Creating Statistics ..."
New-Item "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV" -ItemType Directory -Force | Out-Null
New-Item "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX" -ItemType Directory -Force | Out-Null
# ActivityDisplayName --> Activity (Stats)
$Total = (Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Select-Object ActivityDisplayName | Measure-Object).Count
Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8 | Group-Object ActivityDisplayName | Select-Object @{Name='Activity'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\ActivityDisplayName.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\ActivityDisplayName.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\ActivityDisplayName.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\ActivityDisplayName.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX\ActivityDisplayName.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Activity" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - Activity
$Cells = "A:C"
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Add application",$A1)))' -BackgroundColor Red # Application Creation (Privilege Escalation)
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Add delegated permission grant",$A1)))' -BackgroundColor Red # OAuth Application Permission Grant
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Add eligible member to role in PIM completed (permanent)",$A1)))' -BackgroundColor Red # AZT401 - Privileged Identity Management Role (Privilege Escalation)
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Add eligible member to role in PIM requested (permanent)",$A1)))' -BackgroundColor Red # AZT401 - Privileged Identity Management Role (Privilege Escalation)
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Add member to role completed (PIM activation)",$A1)))' -BackgroundColor Red # AZT401 - Privileged Identity Management Role (Privilege Escalation)
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Add member to role requested (PIM activation)",$A1)))' -BackgroundColor Red # AZT401 - Privileged Identity Management Role (Privilege Escalation)
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Change user password",$A1)))' -BackgroundColor Yellow # A user changes their password. Self-service password reset has to be enabled (for all or selected users) in your organization to allow users to reset their password.
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Consent to application",$A1)))' -BackgroundColor Red # OAuth Application Permission Grant
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Disable account",$A1)))' -BackgroundColor Yellow # Disable a user in Microsoft Entra ID
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Reset user password",$A1)))' -BackgroundColor Red # Administrator resets the password for a user. ATO?
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Set domain authentication",$A1)))' -BackgroundColor Red # Modification of Trusted Domain
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Set federation settings on domain",$A1)))' -BackgroundColor Red # Modification of Trusted Domain
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Update application",$A1)))' -BackgroundColor Red # Modifying Permissions / Adding Permissions (Privilege Escalation)
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Update application - Certificates and secrets management",$A1)))' -BackgroundColor Red # A user added a secret or certificate to an Entra ID Application (Privilege Escalation)
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Update StsRefreshTokenValidFrom Timestamp",$A1)))' -BackgroundColor Yellow # A Refresh Token becomes valid. Entra ID will force users to perform re-authentication whenever this attribute is updated (e.g. after Session Revoke).
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User registered all required security info",$A1)))' -BackgroundColor Red # MFA registered
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User registered security info",$A1)))' -BackgroundColor Red # MFA registered
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User reported unusual sign-in event as not legitimate",$A1)))' -BackgroundColor Red # ATO
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User started security info registration",$A1)))' -BackgroundColor Red # MFA registered
}
}
}
# Category (Stats)
$Total = (Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Select-Object Category | Measure-Object).Count
Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8 | Group-Object Category | Select-Object @{Name='Category'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Category.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Category.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Category.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Category.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX\Category.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Category" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
}
}
}
# LoggedByService --> Service (Stats)
$Total = (Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Select-Object LoggedByService | Measure-Object).Count
Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8 | Group-Object LoggedByService | Select-Object @{Name='Service'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\LoggedByService.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\LoggedByService.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\LoggedByService.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\LoggedByService.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX\LoggedByService.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Service" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
}
}
}
# OperationType (Stats)
$Total = (Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Select-Object OperationType | Measure-Object).Count
Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8 | Group-Object OperationType | Select-Object @{Name='OperationType';Expression={if($_.Name){$_.Name}else{'N/A'}}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\OperationType.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\OperationType.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\OperationType.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\OperationType.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX\OperationType.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "OperationType" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
}
}
}
# PrimaryTarget (Stats)
$Total = (Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Select-Object Target1DisplayName | Measure-Object).Count
Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8 | Group-Object Target1DisplayName | Select-Object @{Name='PrimaryTarget';Expression={if($_.Name){$_.Name}else{'N/A'}}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\PrimaryTarget.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\PrimaryTarget.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\PrimaryTarget.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\PrimaryTarget.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX\PrimaryTarget.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "PrimaryTarget" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
}
}
}
# Status (Stats)
$Total = (Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Select-Object Result | Measure-Object).Count
Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8 | Group-Object Result | Select-Object @{Name='Status'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Status.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Status.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Status.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Status.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX\Status.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Status" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A-C
$WorkSheet.Cells["A:C"].Style.HorizontalAlignment="Center"
}
}
}
# StatusReason (Stats)
$Total = (Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Select-Object ResultReason | Measure-Object).Count
Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8 | Group-Object ResultReason | Select-Object @{Name='StatusReason';Expression={if($_.Name){$_.Name}else{'N/A'}}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\StatusReason.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\StatusReason.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\StatusReason.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\StatusReason.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX\StatusReason.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "StatusReason" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - StatusReason
$Cells = "A:C"
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Access denied. Insufficient privileges to proceed.",$A1)))' -BackgroundColor Red # Denied Access Request
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User failed to register Authenticator App with Code",$A1)))' -BackgroundColor Red # Persistence Attempt
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User registered all required security info.",$A1)))' -BackgroundColor Red # Persistence
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User registered Authenticator App with Code",$A1)))' -BackgroundColor Red # Persistence
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User registered Authenticator App with Notification",$A1)))' -BackgroundColor Red # Persistence
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User registered Authenticator App with Notification and Code",$A1)))' -BackgroundColor Red # Persistence
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User started the registration for Authenticator App with Code",$A1)))' -BackgroundColor Red # Persistence
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User started the registration for Authenticator App with Notification and Code",$A1)))' -BackgroundColor Red # Persistence
}
}
}
# Status / StatusReason (Stats)
$Total = (Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Select-Object Result | Measure-Object).Count
Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8 | Select-Object @{Name='Status'; Expression={$_.Result}},@{Name='StatusReason';Expression={if($_.ResultReason){$_.ResultReason}else{'N/A'}}} | Group-Object Status,StatusReason | Select-Object @{Name='Status'; Expression={ $_.Values[0] }},@{Name='StatusReason'; Expression={ $_.Values[1] }},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Status-StatusReason.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Status-StatusReason.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Status-StatusReason.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\Status-StatusReason.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX\Status-StatusReason.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "Status-StatusReason" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:D1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A and C-D
$WorkSheet.Cells["A:A"].Style.HorizontalAlignment="Center"
$WorkSheet.Cells["C:D"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - StatusReason
$Cells = "A:D"
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("Access denied. Insufficient privileges to proceed.",$B1)))' -BackgroundColor Red # Denied Access Request
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User failed to register Authenticator App with Code",$B1)))' -BackgroundColor Red # Persistence Attempt
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User registered all required security info.",$B1)))' -BackgroundColor Red # Persistence
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User registered Authenticator App with Code",$B1)))' -BackgroundColor Red # Persistence
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User registered Authenticator App with Notification",$B1)))' -BackgroundColor Red # Persistence
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User registered Authenticator App with Notification and Code",$B1)))' -BackgroundColor Red # Persistence
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User started the registration for Authenticator App with Code",$B1)))' -BackgroundColor Red # Persistence
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("User started the registration for Authenticator App with Notification and Code",$B1)))' -BackgroundColor Red # Persistence
}
}
}
# TargetType (Stats)
$Total = (Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Select-Object Target1Type | Measure-Object).Count
Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8 | Group-Object Target1Type | Select-Object @{Name='TargetType';Expression={if($_.Name){$_.Name}else{'N/A'}}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\TargetType.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\TargetType.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\TargetType.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\TargetType.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX\TargetType.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "TargetType" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A-C
$WorkSheet.Cells["A:C"].Style.HorizontalAlignment="Center"
}
}
}
# User-Agent (Stats)
$Total = (Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Where-Object {$_.UserAgent -ne '' } | Select-Object UserAgent | Measure-Object).Count
Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8 | Where-Object {$_.UserAgent -ne '' } | Group-Object UserAgent | Select-Object @{Name='User-Agent';Expression={if($_.Name){$_.Name}else{'N/A'}}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\User-Agent.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\User-Agent.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\User-Agent.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\User-Agent.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX\User-Agent.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "User-Agent" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
# ConditionalFormatting - User-Agent
$Cells = "A:C"
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("AzurePowershell/",$A1)))' -BackgroundColor $Orange # User-Agent associated with scripting/generic HTTP client
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("PostmanRuntime/",$A1)))' -BackgroundColor Red # User-Agent associated with scripting/generic HTTP client
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("PowerShell/5.1",$A1)))' -BackgroundColor $Orange # User-Agent associated with scripting/generic HTTP client
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("PowerShell/7",$A1)))' -BackgroundColor $Orange # User-Agent associated with scripting/generic HTTP client
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("python-requests",$A1)))' -BackgroundColor Red # User-Agent associated with scripting/generic HTTP client
Add-ConditionalFormatting -Address $WorkSheet.Cells["$Cells"] -WorkSheet $WorkSheet -RuleType 'Expression' 'NOT(ISERROR(FIND("python/",$A1)))' -BackgroundColor Red # User-Agent associated with scripting/generic HTTP client
}
}
}
# UserDisplayName (Stats)
$Total = (Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Where-Object {$_.UserDisplayName -ne '' } | Select-Object UserDisplayName | Measure-Object).Count
Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," -Encoding UTF8 | Where-Object {$_.UserDisplayName -ne '' } | Group-Object UserDisplayName | Select-Object @{Name='UserDisplayName'; Expression={$_.Name}},Count,@{Name='PercentUse'; Expression={"{0:p2}" -f ($_.Count / $Total)}} | Sort-Object Count -Descending | Export-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\UserDisplayName.csv" -NoTypeInformation -Encoding UTF8
# XLSX
if (Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\UserDisplayName.csv")
{
if([int](& $xsv count -d "," "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\UserDisplayName.csv") -gt 0)
{
$IMPORT = Import-Csv "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\CSV\UserDisplayName.csv" -Delimiter "," -Encoding UTF8
$IMPORT | Export-Excel -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\Stats\XLSX\UserDisplayName.xlsx" -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter -WorkSheetname "UserDisplayName" -CellStyleSB {
param($WorkSheet)
# BackgroundColor and FontColor for specific cells of TopRow
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:C1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns B-C
$WorkSheet.Cells["B:C"].Style.HorizontalAlignment="Center"
}
}
}
$EndTime_Stats = (Get-Date)
$Time_Stats = ($EndTime_Stats-$StartTime_Stats)
('ADAuditLogsGraph Stats duration: {0} h {1} min {2} sec' -f $Time_Stats.Hours, $Time_Stats.Minutes, $Time_Stats.Seconds) >> "$OUTPUT_FOLDER\Stats.txt"
}
#endregion Stats
Get-Stats
#############################################################################################################################################################################################
#############################################################################################################################################################################################
Function Get-IPLocation {
$StartTime_IPLocation = (Get-Date)
# Count IP addresses
Write-Output "[Info] Data Enrichment w/ IPinfo.io ..."
New-Item "$OUTPUT_FOLDER\IpAddress" -ItemType Directory -Force | Out-Null
if (!(Test-Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv"))
{
Write-Host "[Error] 'Untouched.csv' NOT found." -ForegroundColor Red
Write-Host ""
Stop-Transcript
$Host.UI.RawUI.WindowTitle = "$DefaultWindowsTitle"
Exit
}
$Data = Import-Csv -Path "$OUTPUT_FOLDER\ADAuditLogsGraph\CSV\Untouched.csv" -Delimiter "," | Where-Object {$_.IPAddress -ne '' } | Select-Object -ExpandProperty IPAddress
$Unique = $Data | Sort-Object -Unique
$Unique | Out-File "$OUTPUT_FOLDER\IPAddress\IP-All.txt"
$Count = ($Unique | Measure-Object).Count
$Total = ($Data | Measure-Object).Count
Write-Output "[Info] $Count 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"
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"
# 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::|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"
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"
# 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" # 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" -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" -Append
}
}
# Check IPinfo Subscription Plan (https://ipinfo.io/pricing)
if (Test-Path "$($IPinfo)")
{
Write-Output "[Info] Checking IPinfo Subscription Plan ..."
[int]$TotalRequests = & $IPinfo quota | Select-String -Pattern "Total Requests" | ForEach-Object{($_ -split "\s+")[-1]}
[int]$RemainingRequests = & $IPinfo 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 ($TotalRequests -eq "50000") {Write-Output "[Info] IPinfo Subscription: Free ($TotalMonth Requests/Month)`n[Info] $RemainingMonth Requests left this month"} # No Privacy Detection
elseif ($TotalRequests -eq "150000"){Write-Output "[Info] IPinfo Subscription: Basic"} # No Privacy Detection
elseif ($TotalRequests -eq "250000"){Write-Output "[Info] IPinfo Subscription: Standard"} # Privacy Detection
elseif ($TotalRequests -eq "500000"){Write-Output "[Info] IPinfo Subscription: Business"} # Privacy Detection
else {Write-Output "[Info] IPinfo Subscription Plan: Enterprise"} # Privacy Detection
}
# 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"
# Access Token
# https://ipinfo.io/signup?ref=cli
if (!("$Token" -eq "access_token"))
{
# Summarize IPs
# https://ipinfo.io/summarize-ips
# TXT (lists VPNs)
Get-Content "$OUTPUT_FOLDER\IPAddress\IP.txt" | & $IPinfo summarize -t $Token | Out-File "$OUTPUT_FOLDER\IPAddress\IPinfo\Summary.txt"
# CSV --> No Privacy Detection --> Standard ($249/month w/ 250k lookups)
Get-Content "$OUTPUT_FOLDER\IPAddress\IP.txt" | & $IPinfo --csv -t $Token | Out-File "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo.csv"
# Custom CSV (Free)
if (Test-Path "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo.csv")
{
if([int](& $xsv count "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo.csv") -gt 0)
{
$Import = Import-Csv "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo.csv" -Delimiter ","
$Import | Foreach-Object {
New-Object -TypeName PSObject -Property @{
"IP" = $_ | Select-Object -ExpandProperty ip
"City" = $_ | Select-Object -ExpandProperty city
"Region" = $_ | Select-Object -ExpandProperty region
"Country" = $_ | Select-Object -ExpandProperty country
"Country Name" = $_ | Select-Object -ExpandProperty country_name
"EU" = $_ | Select-Object -ExpandProperty isEU
"Location" = $_ | Select-Object -ExpandProperty loc
"ASN" = $_ | Select-Object -ExpandProperty org | ForEach-Object{($_ -split "\s+")[0]}
"OrgName" = $_ | Select-Object -ExpandProperty org | ForEach-Object {$_ -replace "^AS[0-9]+ "} # OrgName
"Postal Code" = $_ | Select-Object -ExpandProperty postal
"Timezone" = $_ | Select-Object -ExpandProperty timezone
}
} | Select-Object "IP","City","Region","Country","Country Name","EU","Location","ASN","OrgName","Postal Code","Timezone" | Sort-Object {$_.ip -as [Version]} | ConvertTo-Csv -NoTypeInformation -Delimiter "," | Out-File "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo-Custom.csv"
}
}
# Custom XLSX (Free)
if (Get-Module -ListAvailable -Name ImportExcel)
{
if (Test-Path "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo-Custom.csv")
{
if([int](& $xsv count "$OUTPUT_FOLDER\IPAddress\IPinfo\IPinfo-Custom.csv") -gt 0)
{
$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 * -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
$BackgroundColor = [System.Drawing.Color]::FromArgb(50,60,220)
Set-Format -Address $WorkSheet.Cells["A1:K1"] -BackgroundColor $BackgroundColor -FontColor White
# HorizontalAlignment "Center" of columns A-K
$WorkSheet.Cells["A:K"].Style.HorizontalAlignment="Center"
}
}
}
}
# XLSX (Free)