-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver_audit.ps1
More file actions
3030 lines (2742 loc) · 130 KB
/
server_audit.ps1
File metadata and controls
3030 lines (2742 loc) · 130 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
<#
.SYNOPSIS
Enhanced Windows Security Auditor
.DESCRIPTION
Performs comprehensive security audits on local machines and Domain Controllers.
Generates a detailed, expandable HTML report with findings and remediation steps.
Includes: Application inventory, startup programs, security event analysis,
EDR detection (Sophos), and Backup Solution detection (Acronis).
.OUTPUTS
HTML report saved to the user's Desktop.
.NOTES
Version: 4.2
Author: 3ls3if
Changes: Added EDR (Sophos) and Backup (Acronis) detection with exception handling
#>
# ===============================
# ENHANCED EXCEPTION HANDLING CONFIGURATION
# ===============================
$ErrorActionPreference = "Continue" # Changed from "Stop" to continue on errors
$Error.Clear() # Clear any existing errors
$Script:ExecutionErrors = @() # Global variable to track errors
$Date = Get-Date -Format "yyyy-MM-dd_HH-mm"
$ReportPath = "$env:USERPROFILE\Desktop\3ls3if_Security_Audit_$Date.html"
# Function to log errors without stopping execution
function Log-Error {
param(
[string]$FunctionName,
[string]$ErrorMessage,
[string]$ErrorType = "Warning"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$errorEntry = [PSCustomObject]@{
Timestamp = $timestamp
Function = $FunctionName
Message = $ErrorMessage
Type = $ErrorType
}
$Script:ExecutionErrors += $errorEntry
Write-Host "[$ErrorType] $FunctionName`: $ErrorMessage" -ForegroundColor Yellow
}
# Function to safely execute code with error handling
function Invoke-Safely {
param(
[string]$FunctionName,
[scriptblock]$ScriptBlock,
[object]$DefaultReturn = $null,
[switch]$ContinueOnError
)
try {
return & $ScriptBlock
}
catch {
$errorMsg = "Error in $FunctionName`: $_"
Log-Error -FunctionName $FunctionName -ErrorMessage $errorMsg -ErrorType "Error"
if ($ContinueOnError) {
Write-Host " [!] Continuing despite error in $FunctionName..." -ForegroundColor Yellow
}
return $DefaultReturn
}
}
# ===============================
# REMAINING CONFIGURATION
# ===============================
$IsDomainController = Invoke-Safely -FunctionName "Check-DC" -ScriptBlock {
(Get-WmiObject Win32_ComputerSystem).DomainRole -in @(4, 5)
} -DefaultReturn $false
# Security scoring parameters
$ApplicationSecurityScores = @{
"Microsoft" = 10
"Adobe" = 7
"Java" = 4
"Chrome" = 8
"Firefox" = 8
"Zoom" = 6
"TeamViewer" = 3
"AnyDesk" = 2
"VNC" = 3
"PuTTY" = 7
"OpenSSH" = 9
"Python" = 8
"Node.js" = 8
"Docker" = 7
"VMware" = 8
"VirtualBox" = 7
"7-Zip" = 9
"WinRAR" = 6
"VLC" = 9
}
# Known risky startup applications
$RiskyStartupApps = @(
"utorrent", "bittorrent", "torrent",
"cryptominer", "miner", "coinminer",
"keylogger", "spy", "hack", "crack",
"cheat", "trainer", "patch", "loader"
)
# Known safe startup applications
$SafeStartupApps = @(
"windows", "microsoft", "intel", "amd",
"nvidia", "realtek", "broadcom", "dell",
"hp", "lenovo", "acer", "asus", "logitech",
"adobe", "java", "vmware", "citrix", "cisco"
)
# ===============================
# CORE FUNCTIONS (from original script)
# ===============================
function Get-EnhancedGroupMembers {
<#
.SYNOPSIS
Retrieves all members of a specified local group, expanding nested groups.
#>
param (
[Parameter(Mandatory = $true)]
[string]$GroupName,
[Parameter(Mandatory = $false)]
[string]$ComputerName = $env:COMPUTERNAME
)
$AllMembers = @()
try {
Write-Host " [i] Retrieving members of group: $GroupName" -ForegroundColor Cyan
$DirectMembers = Get-LocalGroupMember -Group $GroupName -ErrorAction Stop
foreach ($Member in $DirectMembers) {
$MemberObject = [PSCustomObject]@{
Name = $Member.Name
ObjectClass = $Member.ObjectClass
Source = 'Direct'
ParentGroup = $GroupName
PrincipalType = if ($Member.Name -like "*\$env:COMPUTERNAME*") { 'Local' } elseif ($Member.Name -like "*\*") { 'Domain' } else { 'Unknown' }
}
$AllMembers += $MemberObject
if ($Member.ObjectClass -eq 'Group') {
Write-Host " [+] Found nested group: $($Member.Name)" -ForegroundColor Cyan
}
}
} catch {
$errorMsg = "Error accessing group '$GroupName': $_"
Log-Error -FunctionName "Get-EnhancedGroupMembers" -ErrorMessage $errorMsg
$AllMembers = [PSCustomObject]@{
Name = "Group '$GroupName' not found or inaccessible"
ObjectClass = 'N/A'
Source = 'Error'
ParentGroup = 'N/A'
PrincipalType = 'N/A'
}
}
if ($AllMembers.Count -eq 0) {
$AllMembers = [PSCustomObject]@{
Name = "No members found in '$GroupName'"
ObjectClass = 'N/A'
Source = 'Empty'
ParentGroup = $GroupName
PrincipalType = 'N/A'
}
}
return $AllMembers
}
function Get-InstalledApplications {
<#
.SYNOPSIS
Retrieves installed applications with security scoring.
#>
Write-Host " [i] Collecting installed applications..." -ForegroundColor Cyan
$Applications = @()
# Method 1: Get from registry (32-bit and 64-bit)
$RegPaths = @(
"HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*",
"HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
)
foreach ($Path in $RegPaths) {
try {
if (Test-Path $Path) {
$Apps = Get-ItemProperty $Path -ErrorAction SilentlyContinue | Where-Object {
$null -ne $_.DisplayName -and $_.DisplayName -ne ""
}
foreach ($App in $Apps) {
$AppName = $App.DisplayName
$Publisher = if ($App.Publisher) { $App.Publisher } else { "Unknown" }
$Version = if ($App.DisplayVersion) { $App.DisplayVersion } else { "Unknown" }
$InstallDate = if ($App.InstallDate) { $App.InstallDate } else { "Unknown" }
# Calculate security score
$SecurityScore = 5 # Default score
$ScoreReason = "Neutral application"
# Check against known vendors (using case-insensitive regex escape)
foreach ($Vendor in $ApplicationSecurityScores.Keys) {
# First clean the vendor string, then escape it for regex
$CleanVendor = $Vendor -replace '\\', ''
$EscapedVendor = [regex]::Escape($CleanVendor)
if ($AppName -match $EscapedVendor -or ($Publisher -and $Publisher -match $EscapedVendor)) {
$SecurityScore = $ApplicationSecurityScores[$Vendor]
$ScoreReason = "Known vendor: $CleanVendor"
break
}
}
# Check for risky keywords (case-insensitive)
$RiskyKeywords = @("crack", "keygen", "hack", "patch", "trainer", "cheat", "torrent", "miner")
foreach ($Keyword in $RiskyKeywords) {
if ($AppName -match $Keyword -or ($Publisher -and $Publisher -match $Keyword)) {
$SecurityScore = 1
$ScoreReason = "Contains risky keyword: $Keyword"
break
}
}
# Check for outdated versions of common software
if ($AppName -match "(Java|Adobe|Flash|Reader|Chrome|Firefox)") {
# For Java specifically, check for older versions
if ($AppName -match "Java" -and $Version -match "^(\d+)") {
$MajorVersion = [int]$Matches[1]
if ($MajorVersion -lt 11) {
$SecurityScore = [math]::Min($SecurityScore, 3)
$ScoreReason = "Outdated Java version ($MajorVersion)"
}
}
# For Adobe Flash, flag any version as risky (Flash is deprecated)
if ($AppName -match "Flash" -or $AppName -match "Adobe Flash") {
$SecurityScore = [math]::Min($SecurityScore, 2)
$ScoreReason = "Adobe Flash is deprecated and insecure"
}
}
$Applications += [PSCustomObject]@{
Name = $AppName
Publisher = $Publisher
Version = $Version
InstallDate = $InstallDate
SecurityScore = $SecurityScore
ScoreReason = $ScoreReason
}
}
}
} catch {
$errorMsg = "Error reading registry path $Path`: $_"
Log-Error -FunctionName "Get-InstalledApplications" -ErrorMessage $errorMsg
continue
}
}
# Method 2: Get from Programs and Features (alternative method)
try {
$Programs = Get-WmiObject -Class Win32_Product -ErrorAction SilentlyContinue | Select-Object Name, Version, Vendor, InstallDate
foreach ($Program in $Programs) {
if ($Program.Name) {
$AppName = $Program.Name
# Check if already in list
if ($Applications.Name -notcontains $AppName) {
$SecurityScore = 5
$ScoreReason = "Neutral application"
foreach ($Vendor in $ApplicationSecurityScores.Keys) {
$EscapedVendor = [regex]::Escape($Vendor -replace '\\', '')
if ($AppName -match $EscapedVendor -or ($Program.Vendor -and $Program.Vendor -match $EscapedVendor)) {
$SecurityScore = $ApplicationSecurityScores[$Vendor]
$ScoreReason = "Known vendor: $($Vendor -replace '\\\\', '')"
break
}
}
$Applications += [PSCustomObject]@{
Name = $AppName
Publisher = if ($Program.Vendor) { $Program.Vendor } else { "Unknown" }
Version = if ($Program.Version) { $Program.Version } else { "Unknown" }
InstallDate = if ($Program.InstallDate) {
try {
[DateTime]::ParseExact($Program.InstallDate.Substring(0,8), "yyyyMMdd", $null).ToString("yyyy-MM-dd")
} catch {
$Program.InstallDate
}
} else { "Unknown" }
SecurityScore = $SecurityScore
ScoreReason = $ScoreReason
}
}
}
}
} catch {
$errorMsg = "Could not retrieve programs via WMI: $_"
Log-Error -FunctionName "Get-InstalledApplications" -ErrorMessage $errorMsg
}
# Remove duplicates and sort by security score (lowest first)
try {
# Group by Name and select the first entry for each group
$UniqueApps = $Applications | Group-Object Name | ForEach-Object {
$_.Group | Sort-Object SecurityScore | Select-Object -First 1
} | Sort-Object SecurityScore, Name
} catch {
$errorMsg = "Error processing application list: $_"
Log-Error -FunctionName "Get-InstalledApplications" -ErrorMessage $errorMsg
$UniqueApps = $Applications | Select-Object -First 100 # Return first 100 if sorting fails
}
Write-Host " [✓] Found $($UniqueApps.Count) installed applications" -ForegroundColor Green
return $UniqueApps
}
function Get-StartupApplications {
<#
.SYNOPSIS
Retrieves startup applications with security analysis.
#>
Write-Host " [i] Analyzing startup applications..." -ForegroundColor Cyan
$StartupItems = @()
# Check common startup locations
$StartupLocations = @(
@{Path = "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup"; Type = "User Startup"},
@{Path = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"; Type = "System Startup"},
@{Path = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; Type = "Registry (HKLM Run)"},
@{Path = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; Type = "Registry (HKCU Run)"},
@{Path = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"; Type = "Registry (HKLM RunOnce)"},
@{Path = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"; Type = "Registry (HKCU RunOnce)"}
)
foreach ($Location in $StartupLocations) {
$Path = $Location.Path
$Type = $Location.Type
try {
if ($Path -like "*\*" -and $Path -notlike "*Registry*") {
# File system path
if (Test-Path $Path) {
$Files = Get-ChildItem -Path $Path -ErrorAction SilentlyContinue
foreach ($File in $Files) {
$Assessment = "Review Recommended"
$RiskLevel = "Medium"
$Reason = "Startup application"
# Analyze the startup item
$FileName = $File.Name.ToLower()
# Check for known safe applications
$IsSafe = $false
foreach ($SafeApp in $SafeStartupApps) {
if ($FileName -match $SafeApp) {
$Assessment = "Likely Safe"
$RiskLevel = "Low"
$Reason = "Known safe application: $SafeApp"
$IsSafe = $true
break
}
}
# Check for risky applications if not already marked safe
if (-not $IsSafe) {
foreach ($RiskyApp in $RiskyStartupApps) {
if ($FileName -match $RiskyApp) {
$Assessment = "Potentially Risky"
$RiskLevel = "High"
$Reason = "Contains risky keyword: $RiskyApp"
break
}
}
}
# Check file properties
try {
$FileVersion = (Get-ItemProperty -Path $File.FullName -ErrorAction SilentlyContinue).VersionInfo.FileVersion
if (-not $FileVersion) { $FileVersion = "Unknown" }
} catch {
$FileVersion = "Unknown"
}
$StartupItems += [PSCustomObject]@{
Name = $File.Name
Path = $File.FullName
Type = $Type
Assessment = $Assessment
RiskLevel = $RiskLevel
Reason = $Reason
FileVersion = $FileVersion
LastModified = $File.LastWriteTime.ToString("yyyy-MM-dd HH:mm")
}
}
}
} else {
# Registry path
if (Test-Path $Path) {
$RegEntries = Get-ItemProperty -Path $Path -ErrorAction SilentlyContinue
$RegEntries.PSObject.Properties | Where-Object {
$_.Name -notin @("PSPath", "PSParentPath", "PSChildName", "PSDrive", "PSProvider")
} | ForEach-Object {
$RegValue = $_.Value
$RegName = $_.Name
$Assessment = "Review Recommended"
$RiskLevel = "Medium"
$Reason = "Registry startup entry"
# Analyze registry entry
$RegValueLower = $RegValue.ToLower()
# Check for known safe applications
$IsSafe = $false
foreach ($SafeApp in $SafeStartupApps) {
if ($RegValueLower -match $SafeApp -or $RegName.ToLower() -match $SafeApp) {
$Assessment = "Likely Safe"
$RiskLevel = "Low"
$Reason = "Known safe application: $SafeApp"
$IsSafe = $true
break
}
}
# Check for risky applications
if (-not $IsSafe) {
foreach ($RiskyApp in $RiskyStartupApps) {
if ($RegValueLower -match $RiskyApp -or $RegName.ToLower() -match $RiskyApp) {
$Assessment = "Potentially Risky"
$RiskLevel = "High"
$Reason = "Contains risky keyword: $RiskyApp"
break
}
}
}
# Check for suspicious paths
if ($RegValueLower -match "(temp|tmp|appdata|local settings|\.\\.*)") {
if ($Assessment -eq "Review Recommended") {
$Assessment = "Suspicious Location"
$RiskLevel = "Medium"
$Reason = "Starts from temporary or hidden location"
}
}
$StartupItems += [PSCustomObject]@{
Name = $RegName
Path = $RegValue
Type = $Type
Assessment = $Assessment
RiskLevel = $RiskLevel
Reason = $Reason
FileVersion = "N/A (Registry)"
LastModified = "N/A"
}
}
}
}
} catch {
$errorMsg = "Error checking startup location $Path`: $_"
Log-Error -FunctionName "Get-StartupApplications" -ErrorMessage $errorMsg
continue
}
}
# Also check scheduled tasks that run at startup
try {
$StartupTasks = Get-ScheduledTask -ErrorAction SilentlyContinue | Where-Object {
$_.Triggers | Where-Object { $_.StartBoundary -like "*AtStartup*" -or $_.Enabled -eq $true }
} | Select-Object -First 10
foreach ($Task in $StartupTasks) {
$TaskName = $Task.TaskName
$TaskPath = $Task.TaskPath
$Assessment = "Review Recommended"
$RiskLevel = "Medium"
$Reason = "Scheduled task at startup"
$StartupItems += [PSCustomObject]@{
Name = $TaskName
Path = $TaskPath
Type = "Scheduled Task"
Assessment = $Assessment
RiskLevel = $RiskLevel
Reason = $Reason
FileVersion = "N/A (Scheduled Task)"
LastModified = "N/A"
}
}
} catch {
$errorMsg = "Could not retrieve scheduled tasks: $_"
Log-Error -FunctionName "Get-StartupApplications" -ErrorMessage $errorMsg
}
Write-Host " [✓] Found $($StartupItems.Count) startup items" -ForegroundColor Green
try {
return $StartupItems | Sort-Object RiskLevel -Descending
} catch {
return $StartupItems # Return unsorted if sorting fails
}
}
function Get-SecurityEvents {
<#
.SYNOPSIS
Retrieves critical security events from Windows Event Logs.
#>
Write-Host " [i] Analyzing security events..." -ForegroundColor Cyan
$SecurityEvents = @()
# Define critical event IDs to look for
$CriticalEventIDs = @{
# Account Management
4720 = "A user account was created"
4722 = "A user account was enabled"
4723 = "An attempt was made to change an account's password"
4724 = "An attempt was made to reset an account's password"
4725 = "A user account was disabled"
4726 = "A user account was deleted"
4738 = "A user account was changed"
# Logon Events
4624 = "An account was successfully logged on"
4625 = "An account failed to log on"
4634 = "An account was logged off"
4648 = "A logon was attempted using explicit credentials"
4672 = "Special privileges assigned to new logon"
# Security Events
4688 = "A new process has been created"
4697 = "A service was installed in the system"
4698 = "A scheduled task was created"
4699 = "A scheduled task was deleted"
4700 = "A scheduled task was enabled"
4701 = "A scheduled task was disabled"
4702 = "A scheduled task was updated"
# Audit Events
4719 = "System audit policy was changed"
4902 = "The Per-user audit policy table was created"
4907 = "Auditing settings on object were changed"
# Privilege Use
4673 = "A privileged service was called"
4674 = "An operation was attempted on a privileged object"
# System Events
4616 = "System time was changed"
5024 = "The Windows Firewall Service has started successfully"
5025 = "The Windows Firewall Service has been stopped"
5031 = "The Windows Firewall Service blocked an application from accepting incoming connections"
}
try {
# Get events from last 7 days
$StartTime = (Get-Date).AddDays(-7)
# Get Security events
$Events = Get-WinEvent -LogName "Security" -MaxEvents 100 -ErrorAction SilentlyContinue |
Where-Object { $_.TimeCreated -ge $StartTime -and $_.Id -in $CriticalEventIDs.Keys } |
Select-Object -First 20
foreach ($Event in $Events) {
$EventID = $Event.Id
$EventTime = $Event.TimeCreated.ToString("yyyy-MM-dd HH:mm:ss")
$EventSource = "Security"
# Get event message
$EventMessage = $Event.Message
if ([string]::IsNullOrEmpty($EventMessage)) {
$EventMessage = if ($CriticalEventIDs.ContainsKey($EventID)) {
$CriticalEventIDs[$EventID]
} else {
"Event ID: $EventID"
}
} else {
# Truncate long messages
if ($EventMessage.Length -gt 200) {
$EventMessage = $EventMessage.Substring(0, 200) + "..."
}
}
# Determine severity
$Severity = "Info"
$SeverityClass = "event-info"
# Critical events
if ($EventID -in @(4725, 4726, 4672, 4673, 4719)) {
$Severity = "Critical"
$SeverityClass = "event-critical"
}
# Error events
elseif ($EventID -in @(4625, 5025)) {
$Severity = "Error"
$SeverityClass = "event-error"
}
# Warning events
elseif ($EventID -in @(4720, 4722, 4697, 4698, 4616)) {
$Severity = "Warning"
$SeverityClass = "event-warning"
}
# Success events
elseif ($EventID -in @(4624, 5024)) {
$Severity = "Success"
$SeverityClass = "event-success"
}
$SecurityEvents += [PSCustomObject]@{
Time = $EventTime
EventID = $EventID
Source = $EventSource
Severity = $Severity
Message = $EventMessage
Class = $SeverityClass
}
}
# Also check System and Application logs for security-related events
$OtherLogs = @("System", "Application")
foreach ($LogName in $OtherLogs) {
try {
$LogEvents = Get-WinEvent -LogName $LogName -MaxEvents 20 -ErrorAction SilentlyContinue |
Where-Object {
$_.TimeCreated -ge $StartTime -and
($_.Message -match "error|fail|denied|blocked|attack|malware|virus|threat" -or
$_.Id -in @(1000, 1001, 1002, 1015, 7022, 7023, 7024, 7026, 7031, 7032, 7034))
} |
Select-Object -First 10
foreach ($Event in $LogEvents) {
$EventTime = $Event.TimeCreated.ToString("yyyy-MM-dd HH:mm:ss")
$EventMessage = $Event.Message
if ($EventMessage.Length -gt 150) {
$EventMessage = $EventMessage.Substring(0, 150) + "..."
}
$SecurityEvents += [PSCustomObject]@{
Time = $EventTime
EventID = $Event.Id
Source = $LogName
Severity = "Warning"
Message = $EventMessage
Class = "event-warning"
}
}
} catch {
$errorMsg = "Could not read $LogName log: $_"
Log-Error -FunctionName "Get-SecurityEvents" -ErrorMessage $errorMsg
}
}
} catch {
$errorMsg = "Could not retrieve security events: $_"
Log-Error -FunctionName "Get-SecurityEvents" -ErrorMessage $errorMsg
# Return a placeholder if events can't be accessed
$SecurityEvents = @(
[PSCustomObject]@{
Time = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
EventID = "N/A"
Source = "Audit Script"
Severity = "Warning"
Message = "Could not access Windows Event Logs. Run script as Administrator."
Class = "event-warning"
}
)
}
Write-Host " [✓] Found $($SecurityEvents.Count) security events" -ForegroundColor Green
try {
return $SecurityEvents | Sort-Object Time -Descending
} catch {
return $SecurityEvents # Return unsorted if sorting fails
}
}
function Get-SystemInformation {
<#
.SYNOPSIS
Collects comprehensive system information.
#>
try {
$OS = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue
$ComputerSystem = Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue
if (-not $OS) {
$OS = @{
Caption = "Unknown"
Version = "Unknown"
BuildNumber = "Unknown"
OSArchitecture = "Unknown"
InstallDate = "Unknown"
LastBootUpTime = "Unknown"
}
}
if (-not $ComputerSystem) {
$ComputerSystem = @{
Domain = "Unknown"
Manufacturer = "Unknown"
Model = "Unknown"
TotalPhysicalMemory = 0
}
}
$SysInfo = [PSCustomObject]@{
Hostname = $env:COMPUTERNAME
Domain = $ComputerSystem.Domain
'DC Role' = if ($IsDomainController) { 'Yes' } else { 'No' }
Manufacturer = $ComputerSystem.Manufacturer
Model = $ComputerSystem.Model
'OS Name' = $OS.Caption
'OS Version' = $OS.Version
'OS Build' = $OS.BuildNumber
Architecture = $OS.OSArchitecture
'Install Date' = $OS.InstallDate
'Last Boot Time' = $OS.LastBootUpTime
'System Uptime' = if ($OS.LastBootUpTime -ne "Unknown") {
(New-TimeSpan -Start $OS.LastBootUpTime -End (Get-Date)).ToString("dd\.hh\:mm\:ss")
} else { "Unknown" }
'Total Memory (GB)' = if ($ComputerSystem.TotalPhysicalMemory -gt 0) {
[math]::Round($ComputerSystem.TotalPhysicalMemory / 1GB, 2)
} else { "Unknown" }
'Logged-in User' = "$env:USERDOMAIN\$env:USERNAME"
}
return $SysInfo
} catch {
$errorMsg = "Error collecting system information: $_"
Log-Error -FunctionName "Get-SystemInformation" -ErrorMessage $errorMsg
# Return basic information even if CIM fails
return [PSCustomObject]@{
Hostname = $env:COMPUTERNAME
Domain = "Error retrieving"
'DC Role' = "Unknown"
Manufacturer = "Error retrieving"
Model = "Error retrieving"
'OS Name' = "Windows"
'OS Version' = "Unknown"
'OS Build' = "Unknown"
Architecture = "Unknown"
'Install Date' = "Unknown"
'Last Boot Time' = "Unknown"
'System Uptime' = "Unknown"
'Total Memory (GB)' = "Unknown"
'Logged-in User' = "$env:USERDOMAIN\$env:USERNAME"
}
}
}
function Get-DiskInformation {
<#
.SYNOPSIS
Collects disk usage information.
#>
try {
$Disks = Get-PSDrive -PSProvider FileSystem -ErrorAction SilentlyContinue | Where-Object { $_.Used -or $_.Free } | Select-Object @(
@{N='Drive';E={$_.Name}},
@{N='Description';E={if ($_.DisplayRoot) { $_.DisplayRoot } else { "Local Disk" }}},
@{N='Used (GB)';E={[math]::Round($_.Used / 1GB, 2)}},
@{N='Free (GB)';E={[math]::Round($_.Free / 1GB, 2)}},
@{N='Total (GB)';E={[math]::Round(($_.Used + $_.Free) / 1GB, 2)}},
@{N='Free %';E={if (($_.Used + $_.Free) -gt 0) { [math]::Round(($_.Free / ($_.Used + $_.Free)) * 100, 1) } else { 0 }}}
)
return $Disks
} catch {
$errorMsg = "Error collecting disk information: $_"
Log-Error -FunctionName "Get-DiskInformation" -ErrorMessage $errorMsg
return @(
[PSCustomObject]@{
Drive = "C"
Description = "Local Disk (Error)"
'Used (GB)' = "Error"
'Free (GB)' = "Error"
'Total (GB)' = "Error"
'Free %' = "Error"
}
)
}
}
function Get-NetworkInformation {
<#
.SYNOPSIS
Collects network configuration.
#>
try {
$NetInfo = Get-NetIPConfiguration -Detailed -ErrorAction SilentlyContinue | ForEach-Object {
[PSCustomObject]@{
Interface = $_.InterfaceAlias
'IPv4 Address' = ($_.IPv4Address.IPAddress -join ', ')
Subnet = ($_.IPv4Address.PrefixLength -join ', ')
Gateway = if ($_.IPv4DefaultGateway) { $_.IPv4DefaultGateway.NextHop -join ', ' } else { 'None' }
DNS = ($_.DNSServer.ServerAddresses -join ', ')
MAC = $_.NetAdapter.LinkLayerAddress
Status = $_.NetAdapter.Status
}
}
if (-not $NetInfo) {
$NetInfo = Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Select-Object @(
@{N='Interface';E={$_.InterfaceAlias}},
@{N='IPv4 Address';E={$_.IPAddress}},
@{N='Subnet';E={$_.PrefixLength}},
@{N='MAC';E={(Get-NetAdapter -InterfaceIndex $_.InterfaceIndex -ErrorAction SilentlyContinue).MacAddress}}
)
}
if (-not $NetInfo) {
$NetInfo = @(
[PSCustomObject]@{
Interface = "Network information unavailable"
'IPv4 Address' = "Error retrieving"
Subnet = "N/A"
Gateway = "N/A"
DNS = "N/A"
MAC = "N/A"
Status = "N/A"
}
)
}
return $NetInfo
} catch {
$errorMsg = "Error collecting network information: $_"
Log-Error -FunctionName "Get-NetworkInformation" -ErrorMessage $errorMsg
return @(
[PSCustomObject]@{
Interface = "Error retrieving network info"
'IPv4 Address' = "Error"
Subnet = "Error"
Gateway = "Error"
DNS = "Error"
MAC = "Error"
Status = "Error"
}
)
}
}
function Get-LocalUserAccounts {
<#
.SYNOPSIS
Collects local user account information.
#>
try {
$Users = Get-LocalUser -ErrorAction SilentlyContinue | Select-Object @(
'Name',
'FullName',
'Description',
@{N='Enabled';E={if ($_.Enabled) { 'Yes' } else { 'No' }}},
@{N='Last Logon';E={if ($_.LastLogon) { $_.LastLogon } else { 'Never' }}},
@{N='Password Changed';E={$_.PasswordLastSet}},
@{N='Password Never Expires';E={if ($_.PasswordNeverExpires) { 'Yes' } else { 'No' }}},
@{N='Account Locked';E={if ($_.Locked) { 'Yes' } else { 'No' }}}
)
if (-not $Users) {
$Users = @(
[PSCustomObject]@{
Name = "Local user information unavailable"
FullName = "N/A"
Description = "N/A"
Enabled = "N/A"
'Last Logon' = "N/A"
'Password Changed' = "N/A"
'Password Never Expires' = "N/A"
'Account Locked' = "N/A"
}
)
}
return $Users
} catch {
$errorMsg = "Error collecting local user accounts: $_"
Log-Error -FunctionName "Get-LocalUserAccounts" -ErrorMessage $errorMsg
return @(
[PSCustomObject]@{
Name = "Error retrieving user accounts"
FullName = "Error"
Description = "Error"
Enabled = "Error"
'Last Logon' = "Error"
'Password Changed' = "Error"
'Password Never Expires' = "Error"
'Account Locked' = "Error"
}
)
}
}
function Get-SecurityConfiguration {
<#
.SYNOPSIS
Collects security-related configuration.
#>
$Firewall = $null
$Defender = $null
$SMB = $null
$UAC = $null
$AuditPolicy = $null
# Firewall
try {
$Firewall = Get-NetFirewallProfile -ErrorAction SilentlyContinue | Select-Object Name, Enabled, DefaultInboundAction, DefaultOutboundAction
} catch {
$errorMsg = "Error collecting firewall information: $_"
Log-Error -FunctionName "Get-SecurityConfiguration" -ErrorMessage $errorMsg
$Firewall = [PSCustomObject]@{
Name = "Firewall information unavailable"
Enabled = "Error"
DefaultInboundAction = "Error"
DefaultOutboundAction = "Error"
}
}
# Windows Defender
try {
if (Get-Command Get-MpComputerStatus -ErrorAction SilentlyContinue) {
$DefStatus = Get-MpComputerStatus -ErrorAction SilentlyContinue
$Defender = [PSCustomObject]@{
'Antivirus Enabled' = if ($DefStatus.AntivirusEnabled) { 'Yes' } else { 'No' }
'Real-time Protection' = if ($DefStatus.RealTimeProtectionEnabled) { 'Yes' } else { 'No' }
'Antivirus Signature Age' = if ($DefStatus.AntivirusSignatureAge) { "$($DefStatus.AntivirusSignatureAge) days" } else { 'N/A' }
'Last Quick Scan' = if ($DefStatus.LastQuickScanDateTime) { $DefStatus.LastQuickScanDateTime } else { 'N/A' }
'Last Full Scan' = if ($DefStatus.LastFullScanDateTime) { $DefStatus.LastFullScanDateTime } else { 'N/A' }
}
} else {
$Defender = [PSCustomObject]@{
'Antivirus Enabled' = 'N/A (Defender not available)'
'Real-time Protection' = 'N/A'
'Antivirus Signature Age' = 'N/A'
'Last Quick Scan' = 'N/A'
'Last Full Scan' = 'N/A'
}
}
} catch {
$errorMsg = "Error collecting Defender information: $_"
Log-Error -FunctionName "Get-SecurityConfiguration" -ErrorMessage $errorMsg
$Defender = [PSCustomObject]@{
'Antivirus Enabled' = 'Error retrieving'
'Real-time Protection' = 'Error'
'Antivirus Signature Age' = 'Error'
'Last Quick Scan' = 'Error'
'Last Full Scan' = 'Error'
}
}
# SMB Configuration
try {
$SMB = Get-SmbServerConfiguration -ErrorAction SilentlyContinue | Select-Object @(
@{N='SMBv1 Enabled';E={if ($_.EnableSMB1Protocol) { 'Yes' } else { 'No' }}},
@{N='SMBv2 Enabled';E={if ($_.EnableSMB2Protocol) { 'Yes' } else { 'No' }}},
@{N='SMB Signing Required';E={if ($_.RequireSecuritySignature) { 'Yes' } else { 'No' }}},
@{N='Inactive Sessions Timeout (min)';E={$_.AutoDisconnectTimeout}}
)
} catch {
$errorMsg = "Error collecting SMB configuration: $_"
Log-Error -FunctionName "Get-SecurityConfiguration" -ErrorMessage $errorMsg
$SMB = [PSCustomObject]@{
'SMBv1 Enabled' = "Error"
'SMBv2 Enabled' = "Error"
'SMB Signing Required' = "Error"
'Inactive Sessions Timeout (min)' = "Error"
}
}
# UAC Configuration
try {
$UAC = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -ErrorAction SilentlyContinue | Select-Object @(
@{N='UAC Enabled';E={if ($_.EnableLUA -eq 1) { 'Yes' } else { 'No' }}},
@{N='Admin Approval Mode';E={if ($_.ConsentPromptBehaviorAdmin -ne 0) { 'Yes' } else { 'No' }}},
@{N='Prompt on Elevation';E={if ($_.PromptOnSecureDesktop -eq 1) { 'Yes' } else { 'No' }}}
)
} catch {
$errorMsg = "Error collecting UAC configuration: $_"