-
Notifications
You must be signed in to change notification settings - Fork 0
/
WLCAP2.3.ps1
2615 lines (2462 loc) · 141 KB
/
WLCAP2.3.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
<#
Title: Windows Log Collector & Parser 2.3
Date: 07/01/2014
Author: Ryan Clark
Supported Operating Systems: Windows 7/Windows Server 2008(R2) and newer
Supported PowerShell Versions: PowerShell 3.0+
© Copyright 2024 Northrop Grumman Systems Corporation. Licensed under the MIT License, a copy of which is available at https://opensource.org/license/mit
CHANGELOG
Version: Description: Date:
--------------------------------------------------------------------------------------------------------------------------------------
| 1.0 Initial Release 07-01-14 |
--------------------------------------------------------------------------------------------------------------------------------------
| 1.1 -Fixed issue with $pathDir matching $LogsArchive 07-23-14 |
| -Fixed issue with "Access Denied" when backing up on certain systems by |
| adding "-EnableAllPrivileges" to the WMI object |
--------------------------------------------------------------------------------------------------------------------------------------
| 1.2 -Decreased parsing time and increased proficiency by using xml 08-04-14 |
| queries |
--------------------------------------------------------------------------------------------------------------------------------------
| 1.3 -Filtered out Local Service, IUSR, and computers from event ID 4656 08-08-14 |
| -Added "-parseOnly" paramter (only parses logs stored in $LogsArchive) |
| -Added "-collectOnly" parameter (only collects the logs and does not parse them) |
| -Added "-computerName" parameter (can specify one computer to run against) |
--------------------------------------------------------------------------------------------------------------------------------------
| 1.4 -Added "-quiet" parameter (does not print status to the screen) 08-12-14 |
--------------------------------------------------------------------------------------------------------------------------------------
| 1.5 -Separated Successful and Failed Logons in the report 08-14-14 |
| -Added logon type 11 (cached logons) to the 4624 filter |
| -Separated Successful and Failed Password Changes in the report |
| -Fixed spacing in the report |
| -Added conditional statement in the 4656 filter to ignore usernames ending in "$" |
| -Added logon types in the report |
| -Added an event count to each event category in the report |
--------------------------------------------------------------------------------------------------------------------------------------
| 1.6 -Fixed issue with Clean-Up function putting logs in random folders 08-20-14 |
| -Added the computer name to all the error messages that get written to the report |
| -Filtered out Local Service and computers from event ID 4616 |
| -Added statement to indicate end of script |
| -Fixed archived logs issue (backing up but not cleaning up) |
--------------------------------------------------------------------------------------------------------------------------------------
| 1.7 -Updated Active Directory filter to only list Windows Vista,7,8 and 12-09-14 |
| Server 2008 (R2), 2012 (R2) |
| -Fixed window size error; Changed width from 150 to 128 (128 is max width) |
| -Updated $dateTime to reflect 24-hr clock opposed to standard time to distiguish time |
| of day (AM vs PM) |
| -Fixed issue with system names containing underscores; Reformatted naming scheme for |
| audit log files |
| -Changed the name of the script to not include special characters as this makes problems |
| with running it as a scheduled task. New name is WindowsLogCollectorAndParserX.X.ps1 |
| -Fixed issue with clean-up function not cleaning all of the audit log files. Adding |
| sleep time to the clean-up function seemed to partially fix the issue. Added new |
| function, post-clean, to handle left-over files from the clean-up function. |
| -Added capability of hashing logfiles after copying to verify integrity before removing |
| -Added filter to query the end of each log file for the system name to filter out the |
| events that contain the system name in the username field. |
--------------------------------------------------------------------------------------------------------------------------------------
| 1.8 -Added a query for all logon types on 4624, 4625, 4634 event IDs 06-15-15 |
| -Changed naming convention of saved audit log files to [email protected] |
| -Removed the color-write function and used write-host instead |
| -Added to suppress query to filter out SYSTEM, Local Service, and Network Service |
| from 4624, 4634, 4616, 4656 event IDs |
| -Updated suppress query to filter out SYSTEM from 4720, 4722, 4723, 4724, 4725, 4726, |
| 4781, 4767, and 4732 event IDs |
| -Added screen output to show each log being parsed |
| -Removed -quiet parameter (Not Used) |
| -Fixed formatting for screen output and the report |
| -Added script configuration file so that users would be able to easily modify the |
| config file without editing the script. |
--------------------------------------------------------------------------------------------------------------------------------------
| 1.9 -Fixed issue with script creating a secondary backup of the logs on the root of C: 06-19-15 |
| Added some conditional statements to handle when a backup server is not defined |
| -Built in functionality to run on local (standalone) system if a domain is not found |
--------------------------------------------------------------------------------------------------------------------------------------
| 2.0 -Fixed issue with reading a list of hosts from a file 11-02-15 |
| -Fixed issue with processing/saving logs on the same system the script is ran from |
| -Changed Active Directory computer query to only search for active computers |
| -Added feature to check the accuracy of the host file against a domain computer query |
| and vice-versa |
| -Added a path check in addition to the ping check for system availability |
--------------------------------------------------------------------------------------------------------------------------------------
| 2.1 -Fixed issue with running the script from a remote system and saving the logs on a 01-07-16 |
| system that is being processed. |
| -Added Help Content (To see type Get-Help .\WLCAPx.x.ps1) |
| -Added a check to report if the EventLog was not cleared |
| -Updated list of Event IDs to more accurately show what is being parsed. Some Event |
| IDs were removed because the events would never be generated in a DSS compliant setting. |
| -Added a list of Event IDs captured to the README |
| -Fixed issue with auto rotated application and system logs being put in the parsing |
| folder and not directly in their respective folder. |
| -Separated the successful/failed screen unlock events from the successful/failed |
| logon sections of the report. Successful/Failed screen unlock events will have their |
| own section in the report. This helps clean up the successful/failed logon section of |
| the report for large environments. |
| -Removed Type 7 (Screen Unlock) 4634 (Logoff) events from the report. These events are |
| generated simultaneous to and as a result of a Type 7 (Screen Unlock) 4624 (Logon). |
| Therefore, the events have no value. |
| -Added the parsing of the System log (Event ID 1074) for Shutdowns. The Security log does |
| not provide a shutdown event. |
| -Added logic to parse event IDs 1100, 4739, and 4906. The Event IDs were being pulled but |
| not parsed. |
--------------------------------------------------------------------------------------------------------------------------------------
| 2.2 -Removed check for specific versions of Windows and now just check for "Windows" 08-27-19 |
| -Added Unclassified headers and footers in the report output as well as a "(U)" |
| in the log file and report file names. |
| -Made the collection portion of the script more verbose to show filenames and filepaths |
| -Added Event ID 800, 4688 |
| -Added SYSTEM as the user for event IDs 1100, 4608, 4719, 4739, 4906, 5024, 5025 as |
| there is no user associated with the events. |
| -Filtered out 4625 network logon events generated by SYSTEM |
| -Filtered out DWM-1, DWM-2, DWM-3, UMFD0, UMFD1, UMFD2, UMFD3, from 4624, 4634, and 4648 |
| -Changed over to start-bitstransfer instead of copy-item to show progress for large files |
| -Updated 1074 filter to include support for windows 10, server 2016 and newer |
| Updates Done by Sophie Pokorney: |
| - Added Event ID's: |
| 307, 4670, 4707, 4713, 4727, 4730, 4731, 4732, 4733, 4734, 4744, 4748, 4749, |
| 4753, 4754, 4758, 4759, 4763, 5024, 5025, 6416 |
| - Updated Event ID 800 to specify if it were Powershell, as well as what command was used |
| - Cleaned up and sorted "if" statements in the parsing function |
--------------------------------------------------------------------------------------------------------------------------------------
| 2.3 -Fixed issue with script not copying files (Start-BitsTransfer was the problem), 11-12-20 |
| by reverting back to the old way of copying files (copy-item). |
| -Updated the script to prompt the user to hit enter to exit only if |
| the session is interactive. |
| -Added clean-up routine to collect only |
| -Added Excel output option (requires PS 5.1+) |
| -Events are now stored in objects for easier importing into Excel (requires PS 3+) |
| -Added event ID 4756 per AD STIG V-43712 |
| -Added event ID to message output for powershell commands (event ID 800) |
| -Added event status success/fail to output |
| -Added schTask parameter to add script to scheduled task automatically |
| -Change the way log files are backed up. Using wevtutil vs wmi object |
| -Added a report opener function to ask the user which report to open |
| -Fixed issue with restart events reporting the wrong user |
--------------------------------------------------------------------------------------------------------------------------------------
#>
<#
.SYNOPSIS
The Purpose of WLCAP is to automate the collection and parsing of audit logs on Windows7/Server 2008 and newer
Operating Systems. By default, WLCAP will determine if the system is on a domain or not. If it is on a domain,
it queries the Domain for a list of systems and runs against the systems found. WLCAP first collects the logs
from each system and then parses the logs. If unable to reach a system, WLCAP will report the failure to the
screen in yellow and write it to the report. If no domain is found, WLCAP will run against the local system.
WLCAP is also capable of reading a list of hosts if defined. In each case if WLCAP is unable to save, clear,
or backup the logs, it will report the failure to the screen in red and write it to the report.
.DESCRIPTION
WLCAP is a script that collects and parses eventlogs based on DSS audit requirements.
.EXAMPLE
.\WLCAPx.x.ps1
Executes the script with defaults
.EXAMPLE
.\WLCAPx.x.ps1 -ComputerName SystemX
Executes the script for a designated computer (Where SystemX is the target computer name)
.EXAMPLE
.\WLCAPx.x.ps1 -CollectOnly
Executes the script to only collect the logs and not parse them
.EXAMPLE
.\WLCAPx.x.ps1 -ParseOnly
Executes the script to only parse logs that are in the Logs_Archive folder (designated in the config file)
.EXAMPLE
.\WLCAPx.x.ps1 -schTask
Executes the script to create a scheduled task to execute the script once a week. The account used defaults to SYSTEM.
If running the script for all domain computers, change the username of the task to an account with appropriate permissions.
.NOTES
***The config file must be located in the same directory as the script.
***Windows disables powershell script execution by default. For WLCAP to work, script execution must be turned
on. Do this by opening a powershell window as Admin and enter the following:
"set-executionpolicy -force unrestricted"
.LINK
#>
Param(
[switch]$collectOnly,
[switch]$parseOnly,
[string]$computerName,
[switch]$schTask
)
if ($computerName) {
$computerParam = " -computerName:$computerName"
} #end if
#Run script as admin
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
$arguments = "& '" + $myinvocation.mycommand.definition + "'" + "-schTask:$" + $schTask + " -parseOnly:$" + $parseOnly + " -collectOnly:$" + $collectOnly + $computerParam
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
} #end if
#Script Config
$hostName = ((gwmi win32_computersystem).Name)
$psHost = (get-host).UI.RawUI
$psHost.WindowTitle = "Windows Log Collector & Parser 2.3"
$newSize = $psHost.buffersize
$newSize.height = 5000
$newSize.width = 250
$psHost.buffersize = $newSize
$newSize = $psHost.windowsize
$newSize.height = 50
$newSize.width = 128
$psHost.windowsize = $newSize
$headerBreak = "#########################################################################################################################################################"
$lineBreak = "---------------------------------------------------------------------------------------------------------------------------------------------------------"
$ulineBreak = "_________________________________________________________________________________________________________________________________________________________"
$sysBreak = "*********************************************************************************************************************************************************"
$blankSpace = ""
$sectionHeader = "Date/Time Computer Name User Name Status Event Message"
$scriptPath = Split-Path -Parent $myinvocation.MyCommand.Definition
$schTaskScriptPath = '\"' + $scriptPath + "\" + 'WLCAP2.3.ps1\"'
$WLCAP = "$scriptPath\WLCAP.cfg"
$InstallExcelDir = "$scriptPath\ImportExcel"
$chkImportExcel = (Get-Module ImportExcel).Name
$UI = [Environment]::UserInteractive
#Check for Powershell Version. Version 3 or higher is required.
$PSVer = $PSVersionTable.PSVersion.Major
if ($PSVer -lt 3) {
"Error....Powershell is at version $PSVer and must be version 3 or higher. Install version 3 or higher in order to run this script.
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
}#end if
if ((Test-Path $WLCAP) -eq $True) {
Get-Content $WLCAP | ForEach-Object -Begin {$conf=@{}} -Process { $k = [regex]::Split($_,'='); if (($k[0].CompareTo("") -ne 0) -and ($k[0].StartsWith("[") -ne $True)) { $conf.Add($k[0], $k[1]) } }
} #end if
else {
"Error....Failed to load config file WLCAP.cfg (Incorrect file name or config file is not in the same directory as the script)
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
} #end else
$ErrorActionPreference = $conf.Get_Item("ERROR_ACTION_PREFERENCE")
#Get Config from config file
$LogFolder = $conf.Get_Item("LOG_FOLDER")
$LogsArchive = $conf.Get_Item("LOG_ARCHIVE")
$enableBackupArchive = $conf.Get_Item("ENABLE_BACKUP_ARCHIVE")
$CollectFWEvents = $conf.Get_Item("COLLECT_FW_EVENTS")
$BackupArchive = $conf.Get_Item("BACKUP_ARCHIVE")
$outputFolder = $conf.Get_Item("OUTPUT_FOLDER")
$outputFN = $conf.Get_Item("OUTPUT_FILE")
$enableHostFile = $conf.Get_Item("ENABLE_HOST_FILE")
$hostFile = $conf.Get_Item("HOST_FILE")
$enableHostDiff = $conf.Get_Item("ENABLE_HOST_DIFF")
$enableTextReport = $conf.Get_Item("ENABLE_TEXT_REPORT")
$enableExcelReport = $conf.Get_Item("ENABLE_EXCEL_REPORT")
# Global Variables
$dateTime = "{0:yyyy-MM-dd@HHmmss}" -f [DateTime]::now
$envUser = [System.Environment]::UserName
$outputTextFN = $outputFN + ".txt"
$outputExcelFN = $outputFN + ".xlsx"
$outputFile = "$outputFolder\(U){0}_{1}" -f $dateTime,$outputTextFN
$outputExcel = "$outputFolder\(U){0}_{1}" -f $dateTime,$outputExcelFN
$tempFolder = "Temp"
$localHost = ((gwmi win32_computersystem).Name)
$domainMem = ((gwmi -computername $localHost win32_computersystem).partofdomain)
#Check some required settings in the config file
#Check for LogFolder
if ($LogFolder -eq $null -or $LogFolder -eq "")
{
"Error....Failed to find a value for the LOG_FOLDER setting in the config file.
The LOG_FOLDER setting is required for the script to run (Default is Audit_Logs).
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
} #end if
#Check for LogsArchive
if ($LogsArchive -eq $null -or $LogsArchive -eq "")
{
"Error....Failed to find a path for the LOG_ARCHIVE setting in the config file.
The LOG_ARCHIVE setting is required for the script to run.
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
} #end if
#Check for enableBackupArchive
if ($enableBackupArchive -eq $null -or $enableBackupArchive -eq "")
{
"Error....Failed to find a value for the ENABLE_BACKUP_ARCHIVE setting in the config file.
The ENABLE_BACKUP_ARCHIVE must be set to enabled or disabled for the script to run.
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
} #end if
#Check for enableBackupArchive
if ($enableBackupArchive -eq "enabled" -and $BackupArchive -eq $null -or $enableBackupArchive -eq "enabled" -and $BackupArchive -eq "")
{
"Error....Failed to find a path for the BACKUP_ARCHIVE setting in the config file.
The BACKUP_ARCHIVE setting is required when the ENABLE_BACKUP_ARCHIVE setting is set to enabled.
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
} #end if
#Check for outputFN
if ($outputFN -eq $null -or $outputFN -eq "")
{
"Error....Failed to find a value for the OUTPUT_FILE setting in the config file.
The OUTPUT_FILE setting is required for the script to run (Default is weekly-output.txt).
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
} #end if
#Check for outputFolder
if ($outputFolder -eq $null -or $outputFolder -eq "")
{
"Error....Failed to find a value for the OUTPUT_FOLDER setting in the config file.
The OUTPUT_FOLDER setting is required for the script to run (Default is ""Same path as LOG_ARCHIVE\Audit-output"").
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
} #end if
#Check enableHostFile
if ($enableHostFile -eq $null -or $enableHostFile -eq "")
{
"Error....Failed to find a value for the ENABLE_HOST_FILE setting in the config file.
The ENABLE_HOST_FILE must be set to enabled or disabled for the script to run.
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
} #end if
#Check hostFile
if ($enableHostFile -eq "enabled" -and $hostFile -eq $null -or $enableHostFile -eq "enabled" -and $hostFile -eq "")
{
"Error....Failed to find a path for the HOST_FILE setting in the config file.
The HOST_FILE setting is required when the ENABLE_HOST_FILE setting is set to enabled.
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
} #end if
#Check enableHostDiff
if ($enableHostDiff -eq $null -or $enableHostDiff -eq "")
{
"Error....Failed to find a value for the ENABLE_HOST_DIFF setting in the config file.
The ENABLE_HOST_DIFF must be set to enabled or disabled for the script to run.
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
} #end if
#Check for enableTextReport and enableExcelReport
if (($enableTextReport -eq $null -and $enableExcelReport -eq $null) -or ($enableTextReport -eq "" -and $enableExcelReport -eq "") -or ($enableTextReport -eq "disabled" -and $enableExcelReport -eq "disabled"))
{
"Error....Failed to find a value for the ENABLE_TEXT_REPORT and ENABLE_EXCEL_REPORT setting in the config file.
One of these must be set to enabled for the script to run and produce a report.
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
} #end if
#Check to see if ImportExcel is installed and install if needed.
if ($enableExcelReport -eq "enabled") {
if (! $schTask.IsPresent -and ! $chkImportExcel) {
"Loading Excel Report Module...." | Write-Host -ForegroundColor Green
#cd $InstallExcelDir
#Unblock-File -Path .\InstallModule.ps1
#Invoke-Expression -Command "powershell.exe -ExecutionPolicy Bypass -File .\InstallModule.ps1" | Out-Null
cd $scriptPath
if (! (Test-Path C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ImportExcel)) {
Unblock-File -Path .\ImportExcel-master.zip
Expand-Archive -Path .\ImportExcel-master.zip -DestinationPath .\
Rename-Item -Path .\ImportExcel-master -NewName ImportExcel
Copy-Item -Path .\ImportExcel -Destination C:\Windows\System32\WindowsPowerShell\v1.0\Modules -Recurse
Import-Module ImportExcel -force
}#end if
else {
Import-Module ImportExcel -force
}#end else
#Checking to see if ImportExcel was installed successfully
$chkImportExcel = (Get-Module ImportExcel).Name
echo $chkImportExcel
if (! $chkImportExcel) {
"Error....Failed to install the ImportExcel Module. You may have to install manually. The install script is located here: $InstallExcelDir
Press any key to exit...." | Write-Host -ForegroundColor Red
if ($UI) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
exit
}#end if
clear
}#end if
} # end if
Function Write-ReportHeader
{
if (!(Test-Path $outputFolder))
{
New-Item $outputFolder -type Directory -force | out-Null
} #end if
$headerBreak | Add-Content -Path $outputFile -PassThru | write-host
"####################################################################--UNCLASSIFIED--#####################################################################" | Add-Content -Path $outputFile
"#################################################################--Collection Report--###################################################################" | Add-Content -Path $outputFile -PassThru | write-host
$headerBreak | Add-Content -Path $outputFile -PassThru | write-host
$lineBreak | Add-Content -Path $outputFile -PassThru | write-host
} #end function Print-ReportHeader
Function Hash($thisFile)
{
$algorithm = [System.Security.Cryptography.HashAlgorithm]::Create("SHA1")
$fileStream = ([IO.StreamReader]$thisFile).BaseStream
-join ($algorithm.ComputeHash($fileStream) | foreach { "{0:x2}" -f $_ })
$fileStream.Close()
} #end function Hash
Function Translate-Access ($code) {
foreach ($AL in $code){
switch ($AL) {
"%%4416" {$list += "ReadData (or ListDirectory) "}
"%%4417" {$list += "WriteData (or AddFile) "}
"%%4418" {$list += "AppendData (or AddSubdirectory or CreatePipeInstance) "}
"%%4419" {$list += "ReadEA "}
"%%4420" {$list += "WriteEA`n"}
"%%4421" {$list += "Execute/Traverse "}
"%%4422" {$list += "DeleteChild "}
"%%4423" {$list += "ReadAttributes "}
"%%4424" {$list += "WriteAttributes "}
"%%1537" {$list += "DELETE "}
"%%1538" {$list += "READ_CONTROL "}
"%%1539" {$list += "WRITE_DAC "}
"%%1540" {$list += "WRITE_OWNER "}
"%%1541" {$list += "SYNCHRONIZE "}
"%%1542" {$list += "ACCESS_SYS_SEC "}
default {$list += "Access "}
}#end switch
}#end foreach
return $list
}#end Translate-Access
Function Get-ADComputers
{
#Search for active computers only
$ADComputers = ([adsisearcher]'(&(objectcategory=computer) (! userAccountControl:1.2.840.113556.1.4.803:=2))').findall() | foreach {$_.properties}
foreach ($ADComputer in $ADComputers)
{
$OS = $ADComputer.operatingsystem
$HN = $ADComputer.name
#Only get Windows Operating Systems (just in case the domain has Linux/Unix in the same domain)
if ($OS -match "Windows")
{
$HN
} #end if
} #end foreach
} #end Get-AdComputers function
Function Test-ComputerConnection
{
foreach ($System in $Computers)
{
$computer = $System | %{$_.split('.')[0]}
if ($domainMem -eq $True)
{
$Result = Get-WmiObject -Class win32_pingstatus -Filter "address='$System'"
if ($Result.Statuscode -eq 0 -and (Test-Path "\\$System\C$") -eq $True -and $computer.length -ge 1)
{
Get-BackUpFolder
Copy-ArchivedLogs
} else
{
"- Skipping $computer .. not accessible" | Add-Content -Path $outputFile -PassThru | write-host -ForegroundColor Yellow
} #end else
} elseif($computer.length -ge 1)
{
Get-BackUpFolder
Copy-ArchivedLogs
} #end if
} #end foreach
$lineBreak | Add-Content -Path $outputFile
$blankSpace | Add-Content -Path $outputFile
$blankSpace | Add-Content -Path $outputFile
} #end Test-ComputerConnection
Function Get-BackUpFolder
{
$folder = $computer
if ($domainMem -eq $True)
{
$folders = "$LogsArchive\$folder","$outputFolder","\\$computer\c$\$LogFolder","\\$computer\c$\$LogFolder\$tempFolder"
} else
{
$folders = "$LogsArchive\$folder","$outputFolder","C:\$LogFolder","C:\$LogFolder\$tempFolder"
} #end else
$backupFolder = "$BackupArchive\$folder"
foreach ($dir in $folders)
{
if (!(Test-Path $dir))
{
New-Item $dir -type Directory -force | out-Null
} #end if
} #end foreach
if ($enableBackupArchive -eq "enabled" -and $BackupArchive -ne $null -or $enableBackupArchive -eq "enabled" -and $BackupArchive -ne "" -and !(Test-Path $backupFolder))
{
New-Item $backupFolder -type Directory -force | out-Null
} #end if
Backup-EventLogs($Folder)
} #end Get-BackUpFolder function
Function Backup-EventLogs {
"+ Collecting Logs For $computer" | write-host -ForegroundColor Green
$EventLogs = "Application","Security","System","Windows PowerShell","Microsoft-Windows-PrintService/Operational"
foreach($log in $EventLogs) {
if ($log -match "Microsoft-Windows-PrintService") {
$fileName = $log.split("/")[0]
}
else {
$fileName = $log
}
$logName = "(U){0}.{1}.{2}.evtx" -f $dateTime,$computer,$fileName
" + Saving and clearing $fileName...New name is $logName" | write-host -ForegroundColor DarkGreen
if ($localHost -eq $computer -or $LogsArchive -match "\\\\$computer.*") {
if ($domainMem -eq $True) {
$path = ("\\{1}\c$\$LogFolder\temp\(U){0}.{1}.{2}.evtx" -f $dateTime,$computer,$fileName)
}
else {
$path = ("C:\$LogFolder\temp\(U){0}.{1}.{2}.evtx" -f $dateTime,$computer,$fileName)
} #end else
}
else {
if ($domainMem -eq $True) {
$path = ("\\{1}\c$\$LogFolder\(U){0}.{1}.{2}.evtx" -f $dateTime,$computer,$fileName)
}
else {
$path = ("C:\$LogFolder\(U){0}.{1}.{2}.evtx" -f $dateTime,$computer,$fileName)
} #end else
} #end else
wevtutil epl $log $path /r:$computer
if ($? -eq $True) {
wevtutil cl $log /r:$computer
}
else {
" - Unable to clear event log because backup failed on $computer" | Add-Content -Path $outputFile -PassThru | write-host -ForegroundColor Red
} #end else
Copy-EventLogsToArchive -path $path -Folder $Folder
} #end foreach log
if ($CollectFWEvents -eq "enabled") {
if ($computer -eq $localHost) {
" + Collecting Forwarded Event Logs From $computer" | write-host -ForegroundColor DarkGreen
Backup_FWEvents ([ref]$ColErrs)
} #end if
} #end if
} #end Backup-EventLogs function
Function Backup_FWEvents()
{
$FWEventCount = (get-winevent -ListLog ForwardedEvents).RecordCount
$FWLog = "C:\$LogFolder\(U){0}.{1}.ForwardedEvents.evtx" -f $dateTime,$computer
if (! $FWEventCount -eq "" -or ! $FWEventCount -eq $null)
{
$BkupRES = wevtutil export-log forwardedevents $FWLog
if ($BkupRES -eq $null)
{
$ClrRES = wevtutil clear-log forwardedevents
if ($ClrRES -ne $null)
{
if ($TextReport -eq "enabled")
{
" - Forwarded Event Log was saved but could not be cleared on $computer" | Add-Content -Path $outputFile -PassThru | write-host -ForegroundColor Red
} # end if
$ColErrs.value += "$computer Forwarded Event Log was saved but could not be cleared."
} # end if
} else
{
if ($TextReport -eq "enabled")
{
" - Forwarded Event Log could not be saved on $computer" | Add-Content -Path $outputFile -PassThru | write-host -ForegroundColor Red
} # end else
$ColErrs.value += "$computer Forwarded Event Log could not be saved."
} # end else
} elseif ($TextReport -eq "enabled")
{
" - Forwarded Event Count is 0. There are no Forwarded Events to collect on $computer" | write-host -ForegroundColor Yellow
$ColErrs.value += "$computer Forwarded Event Count is 0. There are no Forwarded Events to collect."
} #end else
} #end Function Backup_FWEvents
Function Copy-EventLogsToArchive($path, $folder, [ref]$ColErrs) {
$shortName = split-path -Path $path -Leaf -Resolve
" + Copying $shortName to primary backup location $LogsArchive to be parsed." | write-host -ForegroundColor DarkGreen
#Start-BitsTransfer -Source $path -Destination "$LogsArchive" -Description "Copying $path to $LogsArchive"
Copy-Item -path $path -destination "$LogsArchive" -force
if ($enableBackupArchive -eq "enabled" -and $BackupArchive -ne $null -or $enableBackupArchive -eq "enabled" -and $BackupArchive -ne "") {
" + Copying $shortName to secondary backup location: $BackupArchive\$folder" | write-host -ForegroundColor DarkGreen
#Start-BitsTransfer -Source $path -Destination "$BackupArchive\$folder" -Description "Copying $path to $BackupArchive\$folder"
Copy-Item -path $path -destination "$BackupArchive\$folder" -force
$testbackupLog = test-path "$BackupArchive\$computer\$logName"
$testbackupLoc = test-path "$BackupArchive\$computer"
$backupHash = Hash("$BackupArchive\$computer\$logName")
} #end if
$logType = $log.LogFileName
$testarchiveLog = test-path "$LogsArchive\$logName"
$origlogHash = Hash($path)
$netlogHash = Hash("$LogsArchive\$logName")
if ($testarchiveLog -eq "True" -and $netlogHash -eq $origlogHash) {
if ($testbackupLoc -eq "True") {
if ($testbackupLog -ne "True" -or $backupHash -ne $origlogHash) {
" - Could not determine if the $logType log on $computer was successfully copied to the backup location. Copy manually." | Add-Content -Path $outputFile -PassThru | write-host -ForegroundColor Red
} #end if
}#end if
remove-item $path -force
}#end if
else {
if ($domainMem -eq $True) {
" - Could not determine if the $logType log on $computer was successfully copied to the archive location.`n Check \\$computer\C$\$LogFolder for logs and backup manually." | Add-Content -Path $outputFile -PassThru | write-host -ForegroundColor Red
}#end if
else {
" - Could not determine if the $logType log on $computer was successfully copied to the archive location.`n Check C:\$LogFolder for logs and backup manually." | Add-Content -Path $outputFile -PassThru | write-host -ForegroundColor Red
} #end else
} #end else
} #end Copy-EventLogsToArchive function
Function Copy-ArchivedLogs
{
#Function Variables
if ($domainMem -eq $True)
{
$archivedLogs = get-childitem "\\$computer\C$\Windows\System32\winevt\Logs\Archive*"
$archlogDir = "\\$computer\C$\Windows\System32\winevt\Logs"
} else
{
$archivedLogs = get-childitem "C:\Windows\System32\winevt\Logs\Archive*"
$archlogDir = "C:\Windows\System32\winevt\Logs"
} #end else
#Look for rotated logs
if ($archivedLogs -ne $null)
{
" + Archived Logs Found on $computer ....Collecting Archived Logs" | write-host -ForegroundColor DarkGreen
foreach ($log in $archivedLogs)
{
$logName = $log.name
$date = $logName | %{$_.split('-')[2,3,4]}
$time = $logName | %{$_.split('-')[5,6,7]} | %{$_.split('.')[0]}
$logType = $logName | %{$_.split('-')[1]}
$joinDate = $date -join "-"
$joinTime = $time -join ""
$renameLog = "(U){0}@{1}.{2}.{3}.evtx" -f $joinDate,$joinTime,$computer,$logType
#Start-BitsTransfer -Source $log -Destination "$LogsArchive\$renameLog" -Description "Copying $log to $LogsArchive\$renameLog"
copy-item -path $log -destination "$LogsArchive\$renameLog" -force
if ($enableBackupArchive -eq "enabled" -and $BackupArchive -ne $null -or $enableBackupArchive -eq "enabled" -and $BackupArchive -ne "") {
#Start-BitsTransfer -Source $log -Destination "$BackupArchive\$computer\$renameLog" -Description "Copying $log to $BackupArchive\$computer\$renameLog"
copy-Item -path $log -destination "$BackupArchive\$computer\$renameLog" -force
$testbackupLog = test-path "$BackupArchive\$computer\$renameLog"
$testbackupLoc = test-path "$BackupArchive\$computer"
$backupHash = Hash("$BackupArchive\$computer\$renameLog")
} #end if
$testarchiveLog = test-path "$LogsArchive\$renameLog"
$origlogHash = Hash("$archlogDir\$logName")
$netlogHash = Hash("$LogsArchive\$renameLog")
if ($testarchiveLog -eq "True" -and $netlogHash -eq $origlogHash) {
if ($testbackupLoc -eq "True") {
if ($testbackupLog -ne "True" -or $backupHash -ne $origlogHash) {
" - Could not determine if the auto archived $logType log on $computer was successfully copied to the backup location. Copy manually." | Add-Content -Path $outputFile -PassThru | write-host -ForegroundColor Red
} #end if
} #end if
remove-item $log -force
} elseif ($domainMem -eq $True) {
" - Could not determine if the auto archived log on $computer was successfully copied to the archive location.`n Check \\$computer\C$\Windows\System32\winevt\Logs\ for logs and collect manually." | Add-Content -Path $outputFile -PassThru | write-host -ForegroundColor Red
}
else {
" - Could not determine if the auto archived log on $computer was successfully copied to the archive location.`n Check C:\Windows\System32\winevt\Logs\ for logs and collect manually." | Add-Content -Path $outputFile -PassThru | write-host -ForegroundColor Red
} #end else
} #foreach
} #end if
} #end Copy-ArchivedLogs function
Function Parse-Logs
{
#Function Variables
$logBack = get-childitem "$LogsArchive\*.evt*" | foreach {$_.Name}
$logCount = $logBack.count
$Sys = (([adsisearcher]"objectcategory=computer").findall()) | foreach {($_.properties).name}
$blankSpace | write-host
$blankSpace | write-host
$headerBreak | write-host
"################################################################--Parsing Audit Logs--###################################################################" | write-host #$this comment is here so that this command doesn't show up in the report
$headerBreak | write-host
$lineBreak | write-host
if (!(Test-Path $outputFolder))
{
New-Item $outputFolder -type Directory -force | out-Null
} #end if
if ($logBack -ne $null)
{
$SLogons = @()
$FLogons = @()
$Logoffs = @()
$SScrnUnlock = @()
$FScrnUnlock = @()
$LockedAccounts = @()
$SPasswdChanges = @()
$FPasswdChanges = @()
$AcctManages = @()
$SysIntegrity = @()
$SecObjects = @()
$CommandLine = @()
$Print = @()
$PolicyChange = @()
$SystemEvents = @()
$RStorageConnect = @()
$PermObjects = @()
#$RStorageAccess = @() #added Too many events generated with 4663
$FileListScript = @()
$AVScript = @()
$AVTScript = @()
"+ Parsing Audit Logs" | write-host -ForegroundColor Green #$this comment is here so that this command doesn't show up in the report
foreach ($logs in $logBack)
{
$sysAccount = $logs.split('.')[1] + "$" #This is to filter out events by the system account.....probably won't work with forwarded event logs
" Parsing $logs" | write-host -ForegroundColor DarkGreen #$this comment is here so that this command doesn't show up in the report
#$Anon = "S-1-5-7"
$IUSR = "S-1-5-17"
$SYSTEM = "S-1-5-18"
$LService = "S-1-5-19"
$NService = "S-1-5-20"
#XPath 1.0 Search Query
$filter = @"
<QueryList>
<Query Id="0" Path="file://$LogsArchive\$logs">
<Select Path="file://$LogsArchive\$logs">
*[System[(EventID=307 or EventID=800 or EventID=1074 or EventID=1100 or EventID=1102 or EventID=4608 or EventID=4616 or EventID=4624 or EventID=4625 or EventID=4634 or EventID=4648 or EventID=4656)]]
or
*[System[(EventID=4670 or EventID=4688 or EventID=4706 or EventID=4707 or EventID=4713 or EventID=4719 or EventID=4720 or EventID=4722 or EventID=4723 or EventID=4724 or EventID=4725 or EventID=4726)]]
or
*[System[(EventID=4727 or EventID=4728 or EventID=4730 or EventID=4731 or EventID=4732 or EventID=4733 or EventID=4734 or EventID=4739 or EventID=4740 or EventID=4744 or EventID=4748 or EventID=4749)]]
or
*[System[(EventID=4753 or EventID=4754 or EventID=4758 or EventID=4759 or EventID=4763 or EventID=4767 or EventID=4781 or EventID=4906 or EventID=5024 or EventID=5025 or EventID=6416 or EventID=4756)]]
</Select>
<Suppress Path="file://$LogsArchive\$logs">
*[EventData[Data[@Name='TargetUserSid']='$SYSTEM']
or
EventData[Data[@Name='TargetUserSid']='$LService']
or
EventData[Data[@Name='TargetUserSid']='$NService']
or
EventData[Data[@Name='TargetDomainName']='Window Manager']
or
EventData[Data[@Name='TargetDomainName']='Font Driver Host']
or
EventData[Data[@Name='LogonType']='3']
and
System[(EventID='4624' or EventID='4634' or EventID='4648')]]
or
*[EventData[Data[@Name='TargetUserName']='$sysAccount']
or
EventData[Data[@Name='SubjectUserSid']='$SYSTEM']
and
System[(EventID='4648')]]
or
*[System[(EventID='4616' or EventID='4656' or EventID='4670' or EventID='4688')]
and
EventData[Data[@Name='SubjectUserSid']='$SYSTEM']
or
EventData[Data[@Name='SubjectUserSid']='$LService']
or
EventData[Data[@Name='SubjectUserSid']='$NService']]
or
*[System[(EventID='4720' or EventID='4722' or EventID='4723' or EventID='4724' or EventID='4725' or EventID='4726' or EventID='4781' or EventID='4767' or EventID='4732')]
and
EventData[Data[@Name='SubjectUserSid']='$SYSTEM']]
or
*[System[(EventID='4688')]
and
EventData[Data[@Name='TokenElevationType']='\%\%1936']
or
EventData[Data[@Name='CommandLine']='\??\C:\WINDOWS\system32\conhost.exe 0xffffffff -ForceV1']]
</Suppress>
</Query>
</QueryList>
"@
$events = get-winevent -oldest -filterXml $filter
if ($events -ne $null)
{
foreach ($logEntry in $events)
{
$time = $logEntry.TimeCreated
$entry = [xml]$logEntry.ToXml()
$sysName = $entry.Event.System.Computer | %{$_.split('.')[0]}
$sysJustify = (15 - $sysName.count) + 4
$eventID = $entry.Event.System.EventID
$evtStatus = $entry.Event.System.Keywords
$success = "0x8020000000000000"
$failure = "0x8010000000000000"
#Setting event status
if ($evtStatus -eq $success) {
$status = "Success"
}#end if
elseif ($evtStatus -eq $failure) {
$status = "Failure"
}#end elseif
else {
$status = "Information"
}#end else
if($eventID -eq 307){
$userName = $entry.Event.UserData.DocumentPrinted.Param3
$fileName = $entry.Event.UserData.DocumentPrinted.Param2
$pages = $entry.Event.UserData.DocumentPrinted.Param8
$usrJustify = (15 - $userName.count) + 4
$message = "$eventID - Printed $fileName ( + $pages + page(s))"
#Create object to store event
$Prnt = [PSCustomObject]@{
Time = $time
System = $sysName
User = $userName
Message = $message
Status = $status
}#end object
$Print += $Prnt
} elseif($eventID."#text" -eq 800) #"#text" needed to work for some reason???
{
$eventID = $eventID."#text" #This is so that the event ID will print out correctly in the report
$eventData = $entry.Event.EventData.Data
$CMD = (($eventData | select-string -pattern 'CommandLine\=.*' -AllMatches | %{$_.Matches} | %{$_.Value}).split('=')[1]).trim()
if ($CMD -notmatch '\\s*$' -and $CMD -notmatch '\$' -and $CMD -notmatch 'Microsoft\.PowerShell\.Core' -and $CMD -notmatch 'RequiredAssemblies'-and $CMD -ne "" -and $CMD -ne $null -and $CMD -notmatch '^C\:\\.*') {
$userName = (($eventData | select-string -pattern 'UserId\=.*' -AllMatches | %{$_.Matches} | %{$_.Value}).split('=')[1]).split('\')[1]
$usrJustify = (15 - $userName.count) + 4
$message = "$eventID - Execution of Powershell Command: $CMD"
#Create object to store event
$CL = [PSCustomObject]@{
Time = $time
System = $sysName
User = $userName
Message = $message
Status = $status
}#end object
$CommandLine += $CL
}
} elseif ($eventID -eq 1074 -or $eventID."#text" -eq 1074) #"#text" needed to work for some reason???
{
#clear userName so it doesn't retain old values
$userName = ""
if ($entry.SelectSingleNode("//*[@Name='param1']")) {
$eventID = $eventID."#text" #This is so that the event ID will print out correctly in the report
$type = ($entry.SelectSingleNode("//*[@Name='param5']"))."#text"
$userName = (($entry.SelectSingleNode("//*[@Name='param7']"))."#text").split('\')[1]
if ($type -match '[Rr]estart') {
$message = "$eventID - Restarted Computer"
} #end if
elseif ($type -match '[Pp]ower [Oo]ff') {
$message = "$eventID - Powered Off Computer"
} #end elseif
else {
$message = "$eventID - $type"
} #end else
}#end if
else {
$eventID = $eventID."#text" #This is so that the event ID will print out correctly in the report
$MSG = @()
$Data = $entry.Event.EventData.Data
foreach ($line in $Data) {
$MSG += $line
} #end foreach
if ($MSG[0] -notmatch '[Ee]xplorer') {
if ($MSG[6] -match '\\') {
$userName = $MSG[6].split('\')[1]
} #end if
else {
$userName = $MSG[6]
} #end else
$type = $MSG[4]
if ($type -match '[Rr]estart') {
$message = "$eventID - Restarted Computer"
} #end if
elseif ($type -match '[Pp]ower [Oo]ff') {
$message = "$eventID - Powered Off Computer"
} #end elseif
else {
$message = "$eventID - $type"
} #end else
}#end if
}#end else
$SI = [PSCustomObject]@{
Time = $time
System = $sysName
User = $userName
Message = $message
Status = $status
}#end object
$SysIntegrity += $SI
} elseif ($eventID -eq 1100)
{
$message = "$eventID - The Eventlog Service Shut Down (Likely A System Shutdown)"
$userName = "SYSTEM"
#Create object to store event
$SI = [PSCustomObject]@{
Time = $time
System = $sysName
User = $userName
Message = $message
Status = $status
}#end object
$SysIntegrity += $SI
} elseif ($eventID -eq 1102)
{
$userName = $entry.Event.UserData.LogFileCleared.SubjectUserName
$usrJustify = (15 - $userName.count) + 4
$message = "$eventID - Cleared The Event Log"
#Create object to store event
$SI = [PSCustomObject]@{
Time = $time
System = $sysName
User = $userName
Message = $message
Status = $status
}#end object
$SysIntegrity += $SI
} elseif ($eventID -eq 4608)
{
$message = "$eventID - System Started Up"
$userName = "SYSTEM"
#Create object to store event
$SI = [PSCustomObject]@{
Time = $time
System = $sysName
User = $userName
Message = $message
Status = $status
}#end object