-
Notifications
You must be signed in to change notification settings - Fork 0
/
Invoke-Power-Nessie.ps1
2335 lines (2125 loc) · 125 KB
/
Invoke-Power-Nessie.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
<#
.Synopsis
This script is a combination of extracting, importing, and automating Nessus scan data into the Elastic stack.
*Invoke-Exract_From_Nessus*
Downloads scans from the My Scans folder (or custom folder) and move them to a different folder of your choosing for archival purposes.
*Invoke-Import_Nessus_To_Elasticsearch*
Parses a single Nessus XML report and imports it into Elasticsearch using the _bulk API.
*Invoke-Automate_Nessus_File_Imports*
Automatically checks for any unprocessed .nessus files and ingest them into Elastic.
*Setup-Elastic-Stack*
Use this script to configure an Elastic stack to properly ingest and visualize the Nessus scan data before ingestion.
.DESCRIPTION
This script is useful for automating the downloads of Nessus scan files and importing them into the Elastic stack. The script will be able to allow for some customizations
such as the Nessus scanner host, the location of the downloads, and the Nessus scan folder for which you wish to move the scans
after they have been downloaded (if you so choose). This tool was inspired from the Posh-Nessus script. Due to lack of updates on the Posh-Nessus
project, it seemed easier to call the raw API to perform the bare minimum functions necessary to export
scans out automatically. I appreciate Tenable leaving these core API functions (export scan and scan status) in their product.
Tested for Nessus 8.9.0+, Latest Tested 10.7.0.
Variable Options
-Nessus_URL "https://127.0.0.1:8834"
-Nessus_File_Download_Location "C:\Nessus"
-Nessus_Access_Key "redacted"
-Nessus_Secret_Key "redacted"
-Nessus_Source_Folder_Name "My Scans"
-Nessus_Archive_Folder_Name "Archive-Ingested"
-Nessus_Export_Scans_From_Today "false"
-Nessus_Export_Day "01/11/2021"
-Nessus_Export_Custom_Extended_File_Name_Attribute "_scanner1"
-Nessus_Export_All_Scan_History "false"
-Elasticsearch_URL "http://127.0.0.1:9200"
-Elasticsearch_Index_Name "logs-nessus.vulnerability"
-Elasticsearch_Api_Key "redacted"
-Nessus_Base_Comparison_Scan_Date @("3/5/2024","3/6/2024")
-Look_Back_Time_In_Days 7,
-Look_Back_Iterations 3,
-Elasticsearch_Scan_Filter @("scan_1","scan2")
-Elasticsearch_Scan_Filter_Type "include",
-Remote_Elasticsearch_URL "http://127.0.0.1:9200"
-Remote_Elasticsearch_Index_Name = "logs-nessus.vulnerability-summary",
-Remote_Elasticsearch_Api_Key "redacted"
-Execute_Patch_Summarization "true"
-Kibana_URL "http://127.0.0.1:5601"
-Kibana_Export_PDF_URL ""
-Kibana_Export_CSV_URL ""
-Email_From ""
-Email_To ""
-SMTP_Server ""
-Email_CC ""
-Configuration_File_Path ""
.EXAMPLE
.\Invoke-Power-Nessie.ps1 -Nessus_URL "https://127.0.0.1:8834" -Nessus_File_Download_Location "C:\Nessus" -Nessus_Access_Key "redacted" -Nessus_Secret_Key "redacted" -Nessus_Source_Folder_Name "My Scans" -Nessus_Archive_Folder_Name "Archive-Ingested" -Nessus_Export_Scans_From_Today "false" -Nessus_Export_Day "01/11/2021" -Nessus_Export_Custom_Extended_File_Name_Attribute "_scanner1" -Elasticsearch_URL "http://127.0.0.1:9200" -Elasticsearch_Index_Name "logs-nessus.vulnerability" -Elasticsearch_Api_Key "redacted"
#>
Param (
# Nessus URL. (default - https://127.0.0.1:8834)
[Parameter(Mandatory=$false)]
$Nessus_URL = "https://127.0.0.1:8834",
# The location where you wish to save the extracted Nessus files from the scanner (default - Nessus_Exports)
[Parameter(Mandatory=$false)]
$Nessus_File_Download_Location = "Nessus_Exports",
# The location of a specifc Nessus file for processing.
[Parameter(Mandatory=$false)]
$Nessus_XML_File,
# Nessus Access Key
[Parameter(Mandatory=$false)]
$Nessus_Access_Key = $null,
# Nessus Secret Key
[Parameter(Mandatory=$false)]
$Nessus_Secret_Key = $null,
# The source folder for where the Nessus scans live in the UI. (default - "My Scans")
[Parameter(Mandatory=$false)]
$Nessus_Source_Folder_Name = "My Scans",
# The destination folder in Nessus UI for where you wish to move your scans for archive. (default - none - scans won't move)
[Parameter(Mandatory=$false)]
$Nessus_Archive_Folder_Name = $null,
# The scan name you want to delete the older scan from (default - none - scans won't get deleted)
[Parameter(Mandatory=$false)]
$Nessus_Scan_Name_To_Delete_Oldest_Scan = $null,
# Use this setting if you wish to only export the scans on the day the scan occurred. (default - false)
[Parameter(Mandatory=$false)]
$Nessus_Export_Scans_From_Today = $null,
# Use this setting if you want to export scans for the specific day that the scan or scans occurred. (example - 11/07/2023)
[Parameter(Mandatory=$false)]
$Nessus_Export_Day = $null,
# Added atrribute for the end of the file name for uniqueness when using with multiple scanners. (example - _scanner1)
[Parameter(Mandatory=$false)]
$Nessus_Export_Custom_Extended_File_Name_Attribute = $null,
# Use this setting to configure the behaviour for exporting more than just the latest scan. Options are:
# Not configured or false, then the latest scan is exported.
# "true" : exports all scan history.
[Parameter(Mandatory=$false)]
$Nessus_Export_All_Scan_History = $null,
# Add Elasticsearch URL to automate Nessus import (default - https://127.0.0.1:9200)
[Parameter(Mandatory=$false)]
$Elasticsearch_URL = "https://127.0.0.1:9200",
# Add Elasticsearch index name to automate Nessus import (default - logs-nessus.vulnerability)
[Parameter(Mandatory=$false)]
$Elasticsearch_Index_Name = "logs-nessus.vulnerability",
# Add Elasticsearch API key to automate Nessus import
[Parameter(Mandatory=$false)]
$Elasticsearch_Api_Key = $null,
# Add Kibana URL for setup. (default - https://127.0.0.1:5601)
[Parameter(Mandatory=$false)]
$Kibana_URL = "https://127.0.0.1:5601",
# Add POST URL to call generation of PDF from outside Kibana(Share->PDF Reports->Advanced options->Copy POST Url)
[Parameter(Mandatory=$false)]
$Kibana_Export_PDF_URL = $null,
# Add POST URL to call generation of CSV from outside Kibana(Share->CSV Reports->Advanced options->Copy POST Url)
[Parameter(Mandatory=$false)]
$Kibana_Export_CSV_URL = $null,
# Sender email address (<SOC> [email protected])
[Parameter(Mandatory=$false)]
$Email_From = $null,
# Recipient email addresses (can be comma seperated for multiple values using @("[email protected]`","[email protected]"))
[Parameter(Mandatory=$false)]
$Email_To = $null,
# Recipient Carbon Copy (CC) email addresses (can be comma seperated for multiple values using @("[email protected]`","[email protected]"))
[Parameter(Mandatory=$false)]
$Email_CC = $null,
# SMTP server used for sending email using Powershell
[Parameter(Mandatory=$false)]
$Email_SMTP_Server = $null,
# Email Subject Line (default - "Vulnerability Report for $date")
[Parameter(Mandatory=$false)]
$Email_Subject = "Vulnerability Report for $(Get-Date -Format "M/d/yyyy")",
# Email Body Text (default - "Attached is the vulnerability report for $date.")
[Parameter(Mandatory=$false)]
$Email_Body = "Attached is the vulnerability report for $(Get-Date -Format "M/d/yyyy").",
# Selected option for automation
[Parameter(Mandatory=$false)]
$Option_Selected,
##### New For Patch Summarization Feature #####
# Set custom scan dates for which scans you want to compare to for it's historical reference.
# For example, setting $Nessus_Base_Comparison_Scan_Date to 3/5/2024 will use data from 3/5/2024 and then use the configured lookback days to compare to (3 days would be 3/2/2024).
[Parameter(Mandatory=$false)]
$Nessus_Base_Comparison_Scan_Date,
# Look back time for checks
[Parameter(Mandatory=$false)]
$Look_Back_Time_In_Days = 7,
# Iterations to look back for hosts not found in first lookback. (default 3)
[Parameter(Mandatory=$false)]
$Look_Back_Iterations = 3,
# Custom scan names to include or exclude based on vulnerability.report_id (example - @("scan1","scan2"))
[Parameter(Mandatory=$false)]
$Elasticsearch_Scan_Filter = $null,
# Custom scan name filter to be include or exclude (default - include)
[Parameter(Mandatory=$false)]
$Elasticsearch_Scan_Filter_Type = "include",
# Remote index capability - Use these options if you want to index into a different cluster your queried your scan data from. This method is typically used for testing.
# If you don't supply these variables then the source index name, url, etc. are used.
# Add Remote Elasticsearch URL to automate Nessus import (default - https://127.0.0.1:9200)
[Parameter(Mandatory=$false)]
$Remote_Elasticsearch_URL = $null,
# Add Remote Elasticsearch Index Name. Adds -summary as a different data stream not to confuse with vulnerability scan data. Also great for index lifecycle management.
[Parameter(Mandatory=$false)]
$Remote_Elasticsearch_Index_Name = $null,
# Add Remote Elasticsearch API key to ingest summary results into.
[Parameter(Mandatory=$false)]
$Remote_Elasticsearch_Api_Key = $null,
# Optionally execute Patch summarization upon completion of automated export and ingest. (default false)
[Parameter(Mandatory=$false)]
$Execute_Patch_Summarization = "false",
# Optionally use a JSON configuration file (example - configuration.json)
[Parameter(Mandatory=$false)]
$Configuration_File_Path = $null,
# Optionally remove *.processed scans by number of days by file write time. Set at 0 will remove all *.processed scans. Set at 1 will remove all but the last day of scans.
[Parameter(Mandatory=$false)]
$Remove_Processed_Scans_By_Days = $null
)
Begin{
if ($PSVersionTable.PSVersion.Major -ge 7) {
Write-Host "PowerShell version $($PSVersionTable.PSVersion.Major) detected, great!"
} else {
Write-Host "Old version of PowerShell detected $($PSVersionTable.PSVersion.Major). Please install PowerShell 7+. Exiting." -ForegroundColor Red
Write-Host "No scans found." -ForegroundColor Red
Exit
}
# Check for configuration.json file to load configuration settings and populate them all. This will override any arguments passed in for the command line.
if($Configuration_File_Path){
try{
$configurationSettings = Get-Content $Configuration_File_Path | ConvertFrom-Json
$configurationSettingsCount = $($configurationSettings.PSObject.Properties | Where-Object {$_.MemberType -eq "NoteProperty" -and $_.Value -ne $null}).count
if($configurationSettingsCount -gt 0){
Write-Host "Configuration settings ($configurationSettingsCount) found in $(Get-Item $Configuration_File_Path) file." -ForegroundColor Green
}
# Store all variables from the configuration file inside of variables to be used later in the script and make sure not to null out the current variables.
if($null -ne $configurationSettings.Nessus_URL){$Nessus_URL = $configurationSettings.Nessus_URL}
if($null -ne $configurationSettings.Nessus_File_Download_Location){$Nessus_File_Download_Location = $configurationSettings.Nessus_File_Download_Location}
if($null -ne $configurationSettings.Nessus_XML_File){$Nessus_XML_File = $configurationSettings.Nessus_XML_File}
if($null -ne $configurationSettings.Nessus_Access_Key){$Nessus_Access_Key = $configurationSettings.Nessus_Access_Key}
if($null -ne $configurationSettings.Nessus_Secret_Key){$Nessus_Secret_Key = $configurationSettings.Nessus_Secret_Key}
if($null -ne $configurationSettings.Nessus_Source_Folder_Name){$Nessus_Source_Folder_Name = $configurationSettings.Nessus_Source_Folder_Name}
if($null -ne $configurationSettings.Nessus_Archive_Folder_Name){$Nessus_Archive_Folder_Name = $configurationSettings.Nessus_Archive_Folder_Name}
if($null -ne $configurationSettings.Nessus_Scan_Name_To_Delete_Oldest_Scan){$Nessus_Scan_Name_To_Delete_Oldest_Scan = $configurationSettings.Nessus_Scan_Name_To_Delete_Oldest_Scan}
if($null -ne $configurationSettings.Nessus_Export_Scans_From_Today){$Nessus_Export_Scans_From_Today = $configurationSettings.Nessus_Export_Scans_From_Today}
if($null -ne $configurationSettings.Nessus_Export_Day){$Nessus_Export_Day = $configurationSettings.Nessus_Export_Day}
if($null -ne $configurationSettings.Nessus_Export_Custom_Extended_File_Name_Attribute){$Nessus_Export_Custom_Extended_File_Name_Attribute = $configurationSettings.Nessus_Export_Custom_Extended_File_Name_Attribute}
if($null -ne $configurationSettings.Nessus_Export_All_Scan_History){$Nessus_Export_All_Scan_History = $configurationSettings.Nessus_Export_All_Scan_History}
if($null -ne $configurationSettings.Elasticsearch_URL){$Elasticsearch_URL = $configurationSettings.Elasticsearch_URL}
if($null -ne $configurationSettings.Elasticsearch_Index_Name){$Elasticsearch_Index_Name = $configurationSettings.Elasticsearch_Index_Name}
if($null -ne $configurationSettings.Elasticsearch_Api_Key){$Elasticsearch_Api_Key = $configurationSettings.Elasticsearch_Api_Key}
if($null -ne $configurationSettings.Kibana_URL){$Kibana_URL = $configurationSettings.Kibana_URL}
if($null -ne $configurationSettings.Kibana_Export_PDF_URL){$Kibana_Export_PDF_URL = $configurationSettings.Kibana_Export_PDF_URL}
if($null -ne $configurationSettings.Kibana_Export_CSV_URL){$Kibana_Export_CSV_URL = $configurationSettings.Kibana_Export_CSV_URL}
if($null -ne $configurationSettings.Email_From){$Email_From = $configurationSettings.Email_From}
if($null -ne $configurationSettings.Email_To){$Email_To = $configurationSettings.Email_To}
if($null -ne $configurationSettings.Email_CC){$Email_CC = $configurationSettings.Email_CC}
if($null -ne $configurationSettings.Email_SMTP_Server){$Email_SMTP_Server = $configurationSettings.Email_SMTP_Server}
if($null -ne $configurationSettings.Option_Selected){$Option_Selected = $configurationSettings.Option_Selected}
if($null -ne $configurationSettings.Nessus_Base_Comparison_Scan_Date){$Nessus_Base_Comparison_Scan_Date = $configurationSettings.Nessus_Base_Comparison_Scan_Date}
if($null -ne $configurationSettings.Look_Back_Time_In_Days){$Look_Back_Time_In_Days = $configurationSettings.Look_Back_Time_In_Days}
if($null -ne $configurationSettings.Look_Back_Iterations){$Look_Back_Iterations = $configurationSettings.Look_Back_Iterations}
if($null -ne $configurationSettings.Elasticsearch_Scan_Filter){$Elasticsearch_Scan_Filter = $configurationSettings.Elasticsearch_Scan_Filter}
if($null -ne $configurationSettings.Elasticsearch_Scan_Filter_Type){$Elasticsearch_Scan_Filter_Type = $configurationSettings.Elasticsearch_Scan_Filter_Type}
if($null -ne $configurationSettings.Execute_Patch_Summarization){$Execute_Patch_Summarization = $configurationSettings.Execute_Patch_Summarization}
if($null -ne $configurationSettings.Remove_Processed_Scans_By_Days){$Remove_Processed_Scans_By_Days = $configurationSettings.Remove_Processed_Scans_By_Days}
}catch{
$_
Write-Host "`nInvalid JSON file: Settings in configuration file could not be processed. Please check to make sure the file contain valid JSON data. Configuration file path: $Configuration_File_Path" -ForegroundColor Red
}
}else{
Write-Host "No configuration file supplied, using provided command line arguments."
}
$option0 = "0. Setup Elasticsearch and Kibana."
$option1 = "1. Export Nessus files."
$option2 = "2. Ingest a single Nessus file into Elasticsearch (Optional - Patch summarization upon completion)."
$option3 = "3. Ingest all Nessus files from a specified directory into Elasticsearch (Optional - Patch summarization upon completion)."
$option4 = "4. Export and Ingest Nessus files into Elasticsearch (Optional - Patch summarization upon completion)."
$option5 = "5. Purge processed hashes list (Remove list of what files have already been processed)."
$option6 = "6. Compare scan data between scans and export results into Elasticsearch (Patch summarization)."
$option7 = "7. Export PDF or CSV Report from Kibana dashboard and optionally send via Email (Advanced Options - Copy POST URL)."
$option8 = "8. Remove processed scans from local Nessus file download directory (May be used optionally with -Remove_Processed_Scans_By_Days)."
#$option10 = "10. Delete oldest scan from scan history (Future / Only works with Nessus Manager license)"
$quit = "Q. Quit"
$version = "`nVersion 1.3.0"
function Show-Menu {
Write-Host "Welcome to the PowerShell script that can export and ingest Nessus scan files into an Elastic stack!" -ForegroundColor Blue
Write-Host "What would you like to do?" -ForegroundColor Yellow
Write-Host $option0
Write-Host $option1
Write-Host $option2
Write-Host $option3
Write-Host $option4
Write-Host $option5
Write-Host $option6
Write-Host $option7
Write-Host $option8
Write-Host $option10
Write-Host $quit
Write-Host $version
}
# Miscellenous Functions
# Get FolderID from Folder name
function getFolderIdFromName {
param ($folderNames)
$folders = Invoke-RestMethod -Method Get -Uri "$Nessus_URL/folders" -ContentType "application/json" -Headers $headers -SkipCertificateCheck
Write-Host "Folders Found: "
$folders.folders.Name | ForEach-Object {
Write-Host "$_" -ForegroundColor Green
}
$global:sourceFolderId = $($folders.folders | Where-Object {$_.Name -eq $folderNames[0]}).id
$global:archiveFolderId = $($folders.folders | Where-Object {$_.Name -eq $folderNames[1]}).id
}
# Update Scan status
function updateStatus {
#Store the current Nessus Scans and their completing/running status to currentNessusScanData
$global:currentNessusScanDataRaw = Invoke-RestMethod -Method Get -Uri "$Nessus_URL/scans?folder_id=$($global:sourceFolderId)" -ContentType "application/json" -Headers $headers -SkipCertificateCheck
$global:listOfScans = $global:currentNessusScanDataRaw.scans | Select-Object -Property Name,Status,creation_date,id
if ($global:listOfScans) {
Write-Host "Scans found!" -ForegroundColor Green
$global:listOfScans
} else {
Write-Host "No scans found." -ForegroundColor Red
}
}
# Simple epoch to ISO8601 Timestamp converter
function convertToISO {
Param($epochTime)
[datetime]$epoch = '1970-01-01 00:00:00'
[datetime]$result = $epoch.AddSeconds($epochTime)
$newTime = Get-Date $result -Format "o"
return $newTime
}
# Core Functions
function Invoke-Exract_From_Nessus {
Param (
# Nessus URL. (default - https://127.0.0.1:8834)
[Parameter(Mandatory=$false)]
$Nessus_URL,
# The location where you wish to save the extracted Nessus files from the scanner. (default - Nessus_Exports)
[Parameter(Mandatory=$false)]
$Nessus_File_Download_Location,
# Nessus Access Key
[Parameter(Mandatory=$true)]
$Nessus_Access_Key,
# Nessus Secret Key
[Parameter(Mandatory=$true)]
$Nessus_Secret_Key,
# The source folder for where the Nessus scans live in the UI. (default - "My Scans")
[Parameter(Mandatory=$false)]
$Nessus_Source_Folder_Name,
# The destination folder in Nessus UI for where you wish to move your scans for archive. (default - none - scans won't move)
[Parameter(Mandatory=$false)]
$Nessus_Archive_Folder_Name,
# Use this setting if you wish to only export the scans on the day the scan occurred. (default - false)
[Parameter(Mandatory=$false)]
$Nessus_Export_Scans_From_Today,
# Use this setting if you want to export scans for the specific day that the scan or scans occurred. (example - 11/07/2023)
[Parameter(Mandatory=$false)]
$Nessus_Export_Day,
# Added atrribute for the end of the file name for uniqueness when using with multiple scanners. (example - _scanner1)
[Parameter(Mandatory=$false)]
$Nessus_Export_Custom_Extended_File_Name_Attribute,
# Use this setting to configure the behaviour for exporting more than just the latest scan. Options are:
# Not configured or false, then the latest scan is exported.
# "true" : exports all scan history.
[Parameter(Mandatory=$false)]
$Nessus_Export_All_Scan_History = $null
)
#>
$headers = @{'X-ApiKeys' = "accessKey=$Nessus_Access_Key; secretKey=$Nessus_Secret_Key"}
#Don't parse the file downloads because we care about speed!
$ProgressPreference = 'SilentlyContinue'
#Check to see if export scan directory exists, if not, create it!
if ($(Test-Path -Path $Nessus_File_Download_Location) -eq $false) {
Write-Host "Could not find $Nessus_File_Download_Location so creating that directory now."
New-Item $Nessus_File_Download_Location -ItemType Directory
}
#Get FolderID from Folder name
function getFolderIdFromName {
param ($folderNames)
$folders = Invoke-RestMethod -Method Get -Uri "$Nessus_URL/folders" -ContentType "application/json" -Headers $headers -SkipCertificateCheck
Write-Host "Folders Found: "
$folders.folders.Name | ForEach-Object {
Write-Host "$_" -ForegroundColor Green
}
$global:sourceFolderId = $($folders.folders | Where-Object {$_.Name -eq $folderNames[0]}).id
$global:archiveFolderId = $($folders.folders | Where-Object {$_.Name -eq $folderNames[1]}).id
}
getFolderIdFromName $Nessus_Source_Folder_Name, $Nessus_Archive_Folder_Name
#Simple epoch to ISO8601 Timestamp converter
function convertToISO {
Param($epochTime)
[datetime]$epoch = '1970-01-01 00:00:00'
[datetime]$result = $epoch.AddSeconds($epochTime)
$newTime = Get-Date $result -Format "o"
return $newTime
}
#Sleep if scans are not finished
function sleep5Minutes {
$sleeps = "Scans not finished, going to sleep for 5 minutes. " + $(Get-Date)
Write-Host $sleeps
Start-Sleep -s 300
}
#Update Scan status
function updateStatus {
#Store the current Nessus Scans and their completing/running status to currentNessusScanData
$global:currentNessusScanDataRaw = Invoke-RestMethod -Method Get -Uri "$Nessus_URL/scans?folder_id=$($global:sourceFolderId)" -ContentType "application/json" -Headers $headers -SkipCertificateCheck
$global:listOfScans = $global:currentNessusScanDataRaw.scans | Select-Object -Property Name,Status,creation_date,id
if ($global:listOfScans) {
Write-Host "Scans found!`nName | Status | Creation Date | Scan ID" -ForegroundColor Green
$global:listOfScans | ForEach-Object {
"{0,-25} {1,-10} {2,-15} {3}" -f $_.name, $_.status, $_.creation_date, $_.id
}
} else {
Write-Host "No scans found." -ForegroundColor Red
}
}
function getScanIdsAndExport{
updateStatus
if ($Nessus_Export_Scans_From_Today -eq "true") {
#Gets current day
$getDate = Get-Date -Format "dddd-d"
$global:listOfScans | ForEach-Object {
if ($(convertToISO($_.creation_date) | Get-Date -format "dddd-d") -eq $getDate) {
Write-Host "Going to export $_"
export -scanId $($_.id) -scanName $($_.name)
Write-Host "Finished export of $_, going to update status..."
}
}
} elseif ($null -ne $Nessus_Export_Day) {
#Gets day entered from arguments
$getDate = $Nessus_Export_Day | Get-Date -Format "dddd-d"
$global:listOfScans | ForEach-Object {
$currentId = $_.id
$scanName = $_.name
$scanHistory = Invoke-RestMethod -Method Get -Uri "$Nessus_URL/scans/$($currentId)?limit=2500" -ContentType "application/json" -Headers $headers -SkipCertificateCheck
$scanHistory.history | ForEach-Object {
if ($(convertToISO($_.creation_date) | Get-Date -format "dddd-d") -eq $getDate) {
#Write-Host "Going to export $_"
Write-Host "Scan History ID Found $($_.history_id)"
$currentConvertedTime = convertToISO($_.creation_date)
export -scanId $currentId -historyId $_.history_id -currentConvertedTime $currentConvertedTime -scanName $scanName
Write-Host "Finished export of $currentId, going to update status..."
} else {
#Write-Host "Nothing found" #$_
#convertToISO($_.creation_date)
}
}
}
} else {
$global:listOfScans | ForEach-Object {
# Grab latest scan from Nessus
if($Nessus_Export_All_Scan_History -ne "true"){
Write-Host "Going to export $($_.name)"
export -scanId $($_.id) -scanName $($_.name)
Write-Host "Finished export of $($_.name), going to update status..."
} else {
# Grab all scans from history
# Get Scan History
$currentId = $_.id
$scanName = $_.name
$scanHistory = Invoke-RestMethod -Method Get -Uri "$Nessus_URL/scans/$($currentId)?limit=2500" -ContentType "application/json" -Headers $headers -SkipCertificateCheck
if ($Nessus_Export_All_Scan_History -eq "true"){
Write-Host "Historical scans found: $($scanHistory.history.count)"
$scanHistory.history | ForEach-Object {
Write-Host "Scan History ID Found $($_.history_id)"
$currentConvertedTime = convertToISO($_.creation_date)
export -scanId $currentId -historyId $_.history_id -currentConvertedTime $currentConvertedTime -scanName $scanName
Write-Host "Finished export of $scanName-$currentId with history ID of $($_.history_id), going to update status..."
}
}
}
}
}
}
function Move-ScanToArchive{
$body = [PSCustomObject]@{
folder_id = $archiveFolderId
} | ConvertTo-Json
$ScanDetails = Invoke-RestMethod -Method Put -Uri "$Nessus_URL/scans/$($scanId)/folder" -Body $body -ContentType "application/json" -Headers $headers -SkipCertificateCheck
Write-Host $ScanDetails -ForegroundColor Yellow
Write-Host "Scan Moved to Archive - Export Complete." -ForegroundColor Green
}
function export ($scanId, $historyId, $currentConvertedTime, $scanName){
Write-Host "Scan: $scanName exporting...`nscan id: $scanId`nhistory id: $historyId"
do {
if($null -eq $currentConvertedTime){
$convertedTime = convertToISO($($global:currentNessusScanDataRaw.scans | Where-Object {$_.id -eq $scanId}).creation_date)
}else{
$convertedTime = $currentConvertedTime
}
$historyIdOrCreationDate = if($historyId){$historyId}else{$_.creation_date}
$exportFileName = Join-Path $Nessus_File_Download_Location $($($convertedTime | Get-Date -Format yyyy_MM_dd).ToString()+"-$($scanName)"+"-$scanId-$historyIdOrCreationDate$($Nessus_Export_Custom_Extended_File_Name_Attribute).nessus")
$exportComplete = 0
$currentScanIdStatus = $($global:currentNessusScanDataRaw.scans | Where-Object {$_.id -eq $scanId}).status
#Check to see if scan is not running or is an empty scan, if true then lets export!
if ($currentScanIdStatus -ne 'running' -and $currentScanIdStatus -ne 'empty' -or $historyId) {
$scanExportOptions = [PSCustomObject]@{
"format" = "nessus"
} | ConvertTo-Json
#Start the export process to Nessus has the file prepared for download
if($historyId){$historyIdFound = "?history_id=$historyId"}else {$historyId = $null}
$exportInfo = Invoke-RestMethod -Method Post "$Nessus_URL/scans/$($scanId)/export$($historyIdFound)" -Body $scanExportOptions -ContentType "application/json" -Headers $headers -SkipCertificateCheck
$exportStatus = ''
while ($exportStatus.status -ne 'ready') {
try {
$exportStatus = Invoke-RestMethod -Method Get "$Nessus_URL/scans/$($ScanId)/export/$($exportInfo.file)/status" -ContentType "application/json" -Headers $headers -SkipCertificateCheck
Write-Host "Export status: $($exportStatus.status)"
}
catch {
Write-Host "An error has occurred while trying to export the scan" -ForegroundColor Red
break
}
Start-Sleep -Seconds 1
}
#Time to download the Nessus scan!
Invoke-RestMethod -Method Get -Uri "$Nessus_URL/scans/$($scanId)/export/$($exportInfo.file)/download" -ContentType "application/json" -Headers $headers -OutFile $exportFileName -SkipCertificateCheck
$exportComplete = 1
Write-Host "Export succeeded!" -ForegroundColor Green
if ($null -ne $Nessus_Archive_Folder_Name) {
#Move scan to archive if folder is configured!
Write-Host "Archive scan folder configured so going to move the scan in the Nessus web UI to $Nessus_Archive_Folder_Name" -Foreground Yellow
Move-ScanToArchive
} else {
Write-Host "Archive folder not configured so not moving scan in the Nessus web UI." -Foreground Yellow
}
}
#If a scan is empty because it hasn't been started skip the export and move on.
if ($currentScanIdStatus -eq 'empty') {
Write-Host "Scan has not been started, therefore skipping this scan."
$exportComplete = 2
}
if ($exportComplete -eq 0 ){
sleep5Minutes
updateStatus
}
} While ($exportComplete -eq 0)
}
$x = 3
do {
getScanIdsAndExport
#Stop Nessus to get a fresh start
if ($global:currentNessusScanData.Status -notcontains 'running') {
} else {
Write-Host 'Nessus has issues, investigate now!'
}
$x = 1
} while ($x -gt 2)
Write-Host "Finished Exporting!" -ForegroundColor White
}
function Invoke-Import_Nessus_To_Elasticsearch {
Param (
# Nessus XML file path
[Parameter(Mandatory=$true)]
$Nessus_XML_File,
# Add Elasticsearch URL to automate Nessus import (default - https://127.0.0.1:9200)
[Parameter(Mandatory=$true)]
$Elasticsearch_URL,
# Add Elasticsearch index name to automate Nessus import (default - logs-nessus.vulnerability)
[Parameter(Mandatory=$true)]
$Elasticsearch_Index_Name,
# Elasticsearch API Key
[Parameter(Mandatory=$true)]
$Elasticsearch_API_Key
)
$ErrorActionPreference = 'Stop'
$nessus = [xml]''
Write-Host "Loading the file $Nessus_XML_File, please wait..." -ForegroundColor Green
$nessus.Load($Nessus_XML_File)
#Elastic Instance (Hard code values here)
#$Elasticsearch_IP = '127.0.0.1'
#$Elasticsearch_Port = '9200'
if ($Elasticsearch_URL -ne "https://127.0.0.1:9200") {
Write-Host "Using the URL you provided for Elastic: $Elasticsearch_URL" -ForegroundColor Green
} else {
Write-Host "Running script with default localhost Elasticsearch URL ($Elasticsearch_URL)." -ForegroundColor Yellow
}
#Nessus User Authenitcation Variables for Elastic
if ($Elasticsearch_API_Key) {
Write-Host "Using the Api Key you provided." -ForegroundColor Green
} else {
Write-Host "Elasticsearch API Key Required! Go here if you don't know how to obtain one - https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html" -ForegroundColor "Red"
break
}
$global:AuthenticationHeaders = @{Authorization = "ApiKey $Elasticsearch_API_Key"}
#Create index name
if ($Elasticsearch_Index_Name -ne "logs-nessus.vulnerability" ) {
Write-Host "Using the Index you provided: $Elasticsearch_Index_Name" -ForegroundColor Green
} else {
$Elasticsearch_Index_Name = "logs-nessus.vulnerability"; Write-Host "No Index was entered, using the default value of $Elasticsearch_Index_Name" -ForegroundColor Yellow
}
function convertEpochSecondsToISO {
Param($epochTime)
$dateTime = [System.DateTimeOffset]::FromUnixTimeMilliseconds($epochTime).DateTime
$newTime = Get-Date $dateTime -Format "o"
return $newTime
}
#Now let the magic happen!
Write-Host "
Starting ingest of $Nessus_XML_File.
The time it takes to parse and ingest will vary on the file size.
Note: Files larger than 1GB could take over 35 minutes.
You can check if data is getting ingested by visiting Kibana and look under Index Management for this index: $Elasticsearch_Index_Name
For debugging uncomment:
#`$data.items | ConvertTo-Json -Depth 5
"
$fileProcessed = (Get-ChildItem $Nessus_XML_File).name
$reportName = $nessus.NessusClientData_v2.Report.name
foreach ($n in $nessus.NessusClientData_v2.Report.ReportHost) {
foreach ($r in $n.ReportItem) {
foreach ($nHPTN_Item in $n.HostProperties.tag) {
#Get useful tag information from the report
switch -Regex ($nHPTN_Item.name)
{
"host-ip" {$ip = $nHPTN_Item."#text"}
"host-fqdn" {$fqdn = $nHPTN_Item."#text"}
"host-rdns" {$rdns = $nHPTN_Item."#text"}
"operating-system-unsupported" {$osu = $nHPTN_Item."#text"}
"system-type" {$systype = $nHPTN_Item."#text"}
"^os$" {$os = $nHPTN_Item."#text"}
"operating-system$" {$opersys = $nHPTN_Item."#text"}
"operating-system-conf" {$operSysConfidence = $nHPTN_Item."#text"}
"operating-system-method" {$operSysMethod = $nHPTN_Item."#text"}
"^Credentialed_Scan" {$credscan = $nHPTN_Item."#text"}
"mac-address" {$macAddr = $nHPTN_Item."#text"}
"HOST_START_TIMESTAMP$" {$hostStart = $nHPTN_Item."#text"}
"HOST_END_TIMESTAMP$" {$hostEnd = $nHPTN_Item."#text"}
}
}
#Convert seconds to milliseconds
$hostStart = $([int]$hostStart*1000)
$hostEnd = if($hostEnd){$([int]$hostEnd*1000)}else{$null}
#Create duration and convert milliseconds to nano seconds
$duration = $(($hostEnd - $hostStart)*1000000)
#Convert start and end dates to ISO
$hostStart = convertEpochSecondsToISO $hostStart
$hostEnd = if($hostEnd){convertEpochSecondsToISO $hostEnd}else{$null}
$obj = [PSCustomObject]@{
"@timestamp" = $hostStart #Remove later for at ingest enrichment
"destination" = [PSCustomObject]@{
"port" = $([Uint16]$r.port)
}
"message" = $n.name + ' - ' + $r.synopsis #Remove later for at ingest enrichment
"event" = [PSCustomObject]@{
"category" = "host" #Remove later for at ingest enrichment
"kind" = "state" #Remove later for at ingest enrichment
"duration" = if($duration){$([long]$duration)}else{$null}
"start" = $hostStart
"end" = if($hostEnd){$hostEnd}else{$null}
"risk_score" = $r.severity
"dataset" = "vulnerability" #Remove later for at ingest enrichment
"provider" = "Nessus" #Remove later for at ingest enrichment
"module" = "Invoke-Power-Nessie"
"severity" = $([Uint16]$r.severity) #Remove later for at ingest enrichment
"url" = (@(if($r.cve){($r.cve | ForEach-Object {"https://cve.mitre.org/cgi-bin/cvename.cgi?name=$_"})}else{$null})) #Remove later for at ingest enrichment
}
"host" = [PSCustomObject]@{
"ip" = $ip
"mac" = (@(if($macAddr){($macAddr.Split([Environment]::NewLine))}else{$null}))
"hostname" = if($fqdn -notmatch "sources" -and ($fqbn)){($fqdn).ToLower()}elseif($rdns){($rdns).ToLower()}else{$null} #Remove later for at ingest enrichment #Also, added a check for an extra "sources" sub field added to the fqbn field
"name" = if($fqdn -notmatch "sources" -and ($fqbn)){($fqdn).ToLower()}elseif($rdns){($rdns).ToLower()}else{$null} #Remove later for at ingest enrichment #Also, added a check for an extra "sources" sub field added to the fqbn field
"os" = [PSCustomObject]@{
"family" = $os
"full" = @(if($opersys){$opersys.Split("`n`r")}else{$null})
"name" = @(if($opersys){$opersys.Split("`n`r")}else{$null})
"platform" = $os
}
}
"log" = [PSCustomObject]@{
"origin" = [PSCustomObject]@{
"file" = [PSCustomObject]@{
"name" = $fileProcessed
}
}
}
"nessus" = [PSCustomObject]@{
"cve" = (@(if($r.cve){($r.cve).ToLower()}else{$null}))
"in_the_news" = if($r.in_the_news){$r.in_the_news}else{$null}
"solution" = $r.solution
"synopsis" = $r.synopsis
"unsupported_os" = if($osu){$osu}else{$null}
"system_type" = $systype
"credentialed_scan" = $credscan
"exploit_available" = $r.exploit_available
"edb-id" = $r."edb-id"
"unsupported_by_vendor" = $r.unsupported_by_vendor
"os_confidence" = $operSysConfidence
"os_identification_method" = $operSysMethod
"rdns" = $rdns
"name_of_host" = $n.name.ToLower()
"cvss" = [PSCustomObject]@{
"vector" = if($r.cvss_vector){$r.cvss_vector}else{$null}
"base_score" = if($r.cvss_base_score){$r.cvss_base_score}else{$null}
"impact_score" = if($r.cvss_impactScore){$r.cvss_impactScore}else{$null}
"temporal_score" = if($r.cvss_temporal_score){$r.cvss_temporal_score}else{$null}
}
"cvss3" = [PSCustomObject]@{
"vector" = if($r.cvss3_vector){$r.cvss3_vector}else{$null}
"base_score" = if($r.cvss3_base_score){$r.cvss3_base_score}else{$null}
"impact_score" = if($r.cvssV3_impactScore){$r.cvssV3_impactScore}else{$null}
"temporal_score" = if($r.cvss3_temporal_score){$r.cvss3_temporal_score}else{$null}
}
"plugin" = [PSCustomObject]@{
"id" = $r.pluginID
"name" = $r.pluginName
"publication_date" = $r.plugin_publication_date
"type" = $r.plugin_type
"output" = $r.plugin_output
"filename" = $r.fname
"modification_date" = if($r.plugin_modification_date){$r.plugin_modification_date}else{$null}
"script_version" = if($r.script_version){$r.script_version}else{$null}
}
"vpr_score" = if($r.vpr_score){$r.vpr_score}else{$null}
"exploit_code_maturity" = if($r.exploit_code_maturity){$r.exploit_code_maturity}else{$null}
"exploitability_ease" = if($r.exploitability_ease){$r.exploitability_ease}else{$null}
"age_of_vuln" = if($r.age_of_vuln){$r.age_of_vuln}else{$null}
"patch_publication_date" = if($r.patch_publication_date){$r.patch_publication_date}else{$null}
"stig_severity" = if($r.stig_severity){$r.stig_severity}else{$null}
"threat" = [PSCustomObject]@{
"intensity_last_28" = if($r.threat_intensity_last_28){$r.threat_intensity_last_28}else{$null}
"recency" = if($r.threat_recency){$r.threat_recency}else{$null}
"sources_last_28" = if($r.threat_sources_last_28){$r.threat_sources_last_28}else{$null}
}
"vuln_publication_date" = if($r.vuln_publication_date){$r.vuln_publication_date}else{$null}
"product_coverage" = if($r.product_coverage){$r.product_coverage}else{$null}
"cea_id" = if($r.'cea-id'){$r.'cea-id'}else{$null}
"cisa_known_exploited" = if($r.'cisa-known-exploited'){$r.'cisa-known-exploited'}else{$null}
"cpe" = if($r.cpe){$r.cpe}else{$null}
"exploited_by_malware" = if($r.exploited_by_malware){$r.exploited_by_malware}else{$null}
"exploited_by_nessus" = if($r.exploited_by_nessus){$r.exploited_by_nessus}else{$null}
"risk_factor" = if($r.risk_factor){$r.risk_factor}else{$null}
"epss_score" = if($r.epss_score){$r.epss_score}else{$null}
}
"network" = [PSCustomObject]@{
"transport" = $r.protocol
"application" = $r.svc_name
}
"vulnerability" = [PSCustomObject]@{
"id" = (@(if($r.cve){($r.cve)}else{$null}))
"category" = $r.pluginFamily
"description" = $r.description
"severity" = $r.risk_factor
"reference" = (@(if($r.see_also){($r.see_also.Split("`n"))}else{$null}))
"report_id" = $reportName
"module" = $r.pluginName
"classification" = (@(if($r.cve){("CVE")}else{$null}))
"score" = [PSCustomObject]@{
"base" = $r.cvss_base_score
"temporal" = $r.cvss_temporal_score
}
}
} | ConvertTo-Json -Compress -Depth 5
$hash += "{`"create`":{ } }`r`n$obj`r`n"
#$Clean up variables
$ip = ''
$fqdn = ''
$osu = ''
$systype = ''
$os = ''
$opersys = ''
$credscan = ''
$macAddr = ''
$hostStart = ''
$hostEnd = ''
$rdns = ''
$operSysConfidence = ''
$operSysMethod = ''
}
#Uncomment below to see the hash
#$hash
$ProgressPreference = 'SilentlyContinue'
$data = Invoke-RestMethod -Uri "$Elasticsearch_URL/$Elasticsearch_Index_Name/_bulk" -Method POST -ContentType "application/x-ndjson; charset=utf-8" -body $hash -Headers $global:AuthenticationHeaders -SkipCertificateCheck
#Error checking
#$data.items | ConvertTo-Json -Depth 5
$hash = ''
}
}
function Invoke-Automate_Nessus_File_Imports {
Param (
# The location where you wish to save the extracted Nessus files from the scanner (default - Nessus_Exports)
[Parameter(Mandatory=$true)]
$Nessus_File_Download_Location,
# Add Elasticsearch URL to automate Nessus import (default - https://127.0.0.1:9200)
[Parameter(Mandatory=$true)]
$Elasticsearch_URL,
# Add Elasticsearch index name to automate Nessus import (default - logs-nessus.vulnerability)
[Parameter(Mandatory=$true)]
$Elasticsearch_Index_Name,
# Elasticsearch Api Key
[Parameter(Mandatory=$true)]
$Elasticsearch_API_Key
)
$ProcessedHashesPath = "ProcessedHashes.txt"
#Check to see if export scan directory exists, if not, create it!
if ($false -eq $(Test-Path -Path $Nessus_File_Download_Location)) {
Write-Host "Could not find $Nessus_File_Download_Location so creating that directory now."
New-Item $Nessus_File_Download_Location -ItemType Directory
}
#Check to see if ProcessedHashses.txt file exists, if not, create it!
if ($false -eq $(Test-Path -Path $processedHashesPath)) {
Write-Host "Could not find $processedHashesPath so creating that file now."
New-Item $processedHashesPath
}
#Check to see if parsedTime.txt file exists, if not, create it!
if ($false -eq $(Test-Path -Path "parsedTime.txt")) {
Write-Host "Could not find parsedTime.txt so creating that file now."
New-Item "parsedTime.txt"
}
#Start ingesting 1 by 1!
$allFiles = Get-ChildItem -Path $Nessus_File_Download_Location -Recurse -Include "*.nessus"
$allProcessedHashes = Get-Content $processedHashesPath
$allFiles | ForEach-Object {
#Check if already processed by name and hash
if ($_.Name -like '*.nessus' -and ($allProcessedHashes -notcontains $($_ | Get-FileHash).Hash)) {
$starting = Get-Date
$Nessus_XML_File = Join-Path $Nessus_File_Download_Location -ChildPath $_.Name
$markProcessed = "$($_.Name).processed"
Write-Host "Going to process $_ now."
Invoke-Import_Nessus_To_Elasticsearch -Nessus_XML_File $_ -Elasticsearch_URL $Elasticsearch_URL -Elasticsearch_Index $Elasticsearch_Index_Name -Elasticsearch_API_Key $Elasticsearch_API_Key
$ending = Get-Date
$duration = $ending - $starting
$($Nessus_XML_File+'-PSNFscript-'+$duration | Out-File $(Resolve-Path parsedTime.txt).Path -Append)
$($_ | Get-FileHash).Hash.toString() | Add-Content $processedHashesPath
Write-Host "$Nessus_XML_File processed in $duration"
Rename-Item -Path $_ -NewName $markProcessed
} else {
Write-Host "The file $($_.Name) doesn't end in .nessus or has already been processed in the $ProcessedHashesPath file. This file is used for tracking what files have been ingested to prevent duplicate ingest of data."
Write-Host "If it's already been processed and you want to process it again, remove the hash from the $ProcessedHashesPath file or just remove it entirely for a clean slate."
}
}
Write-Host "End of automating script!" -ForegroundColor Green
}
function Invoke-Purge_Processed_Hashes_List {
Remove-Item .\ProcessedHashes.txt -Force
}
function Invoke-Revert_Nessus_To_Processed_Rename {
Param (
# The location where you wish to save the extracted Nessus files from the scanner (default - Nessus_Exports)
[Parameter(Mandatory=$true)]
$Nessus_File_Download_Location
)
# Get all files in the directory with the .nessus.processed extension
$allFiles = Get-ChildItem -Path $Nessus_File_Download_Location -Recurse -Include "*.processed"
# Rename each file
foreach ($file in $allFiles) {
$newName = $file.FullName -replace '\.processed$', ''
Rename-Item -Path $file.FullName -NewName $newName -Force
}
}
function Invoke-Purge_Oldest_Scan_From_History {
Param (
[Parameter(Mandatory=$true)]
$Nessus_Scan_Name_To_Delete_Oldest_Scan
)
$headers = @{'X-ApiKeys' = "accessKey=$Nessus_Access_Key; secretKey=$Nessus_Secret_Key"}
# Don't parse the file downloads because we care about speed!
$ProgressPreference = 'SilentlyContinue'
getFolderIdFromName $Nessus_Source_Folder_Name, $Nessus_Archive_Folder_Name
updateStatus
$global:listOfScans | Where-Object -Property name -eq $Nessus_Scan_Name_To_Delete_Oldest_Scan
$scanId = $($global:listOfScans | Where-Object -Property name -eq $Nessus_Scan_Name_To_Delete_Oldest_Scan).id
if($null -eq $scanId){
Write-Host "Invalid scan name entered ($Nessus_Scan_Name_To_Delete_Oldest_Scan) - exiting script" -ForegroundColor Yellow
exit
} else {
Write-Host "Valid scan name found ($Nessus_Scan_Name_To_Delete_Oldest_Scan)" -ForegroundColor Green
}
$scanHistory = Invoke-RestMethod -Method Get -Uri "$Nessus_URL/scans/$($scanId)?limit=2500" -ContentType "application/json" -Headers $headers -SkipCertificateCheck
$scanHistorySorted = $scanHistory.history | Select-Object -Property history_id, @{Name='creation_date'; Expression={convertToISO($_.creation_date)|Get-Date -Format 'MM/dd/yyyy HH:mm:ss'}}, status | Sort-Object -Property creation_date
$oldestStartDate = $scanHistorySorted[0].creation_date
$oldestStatus = $scanHistorySorted[0].status
$oldestHistoryId = $scanHistorySorted[0].history_id
$scanHistorySorted
Write-Host "Found $($($scanHistory.history).count) total scans for $($scanHistory.info.name)"
Write-Host "The oldest scan will be deleted. Details below:`nScan Started: $oldestStartDate`nScan Status: $oldestStatus`nScan History Id: $oldestHistoryId"
try{
# Delete scan
Write-Host "Deleting scan! $Nessus_Scan_Name_To_Delete_Oldest_Scan (Id-$scanId,History Id-$oldestHistoryId)" -ForegroundColor Magenta
$deleteScan = Invoke-RestMethod -Method Delete -Uri "$Nessus_URL/scans/$($scanId)/history/$oldestHistoryId" -ContentType "application/json" -Headers $headers -SkipCertificateCheck
Write-Host "Scan successfully deleted!"
} catch {
Write-Host "Scan could not be deleted. $_"
}
Write-Host "End of oldest scan deletion script!" -ForegroundColor Green
}
### Compare Scans Feature Functions \/ \/ \/
# Create a new date based on shift in days
function dateShift {
param (
$date,
$daysToShiftBackwards
)
$newDate = $((Get-Date $date).AddDays(-$daysToShiftBackwards)) | Get-Date -Format "o" -AsUTC
return $newDate
}
# Get Vulnerability Scan Data
function getVulnData {
param (
$dateAfter,
$dateBefore,
$severity
)
$queryResults = @()
# Create Point In Time Query for pagination (PIT)
$pitSearch = Invoke-RestMethod "$Elasticsearch_URL/$Elasticsearch_Index_Name/_pit?keep_alive=1m" -Method POST -Headers $global:AuthenticationHeaders -ContentType "application/json" -SkipCertificateCheck
$pitID = $pitSearch.id
$getAllHostsWithVulnsQueryBySeverityAllDocs = @"
{
"size": 5000,
"query": {
"bool": {
"must": [],
"filter": [
{
"bool": {
"filter": [
{
"bool": {
"should": [
{
"query_string": {
"fields": [
"_index"
],
"query": "$($Elasticsearch_Index_Name)"
}
}
],
"minimum_should_match": 1
}
},
{
"bool": {
"must": [],
"filter": [
{
"bool": {
"should": [
{
"term": {
"vulnerability.severity": {
"value": "$($severity)"
}
}
}
],
"minimum_should_match": 1
}
}
],
"should": [],
"must_not": []
}
}$Elasticsearch_Custom_Filter
]
}
},
{
"range": {
"@timestamp": {
"format": "strict_date_optional_time",
"gte": "$($dateAfter)",
"lte": "$($dateBefore)"
}
}
}
],
"should": [],
"must_not": []
}
},
"pit": {
"id": "$pitID",
"keep_alive": "1m"
},
"sort": [
{
"_shard_doc": "asc"
}
]