-
Notifications
You must be signed in to change notification settings - Fork 2
/
MalwareCodeScanner.ps1
766 lines (660 loc) · 27.5 KB
/
MalwareCodeScanner.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
<#
Author: Johto Robbie
License: GPLv3
#>
param (
[Parameter(Mandatory = $true)]
[string]$projectFolderPath
)
# Trim the project folder path to remove leading/trailing spaces
$projectFolderPath = $projectFolderPath.Trim()
# Extract the project folder name for output file
$folderName = [System.IO.Path]::GetFileName($projectFolderPath.TrimEnd('\'))
$outputFilePath = "$folderName-scan-results.txt"
$jsonOutputPath = "$folderName-scan-results.json"
$csvOutputPath = "$folderName-scan-results.csv"
# Initialize matches array
$allMatches = @()
# Define detection patterns and rules
$patterns = @(
@{
Type = "Shellcode Patterns"
Patterns = @(
"\b(?:[0-9a-fA-F]{2}[\s,]+){8,}\b", # Basic hex sequences - detect raw shellcode bytes
"\\x[0-9a-fA-F]{2}(?:\\x[0-9a-fA-F]{2}){7,}", # \x format shellcode - common in exploits
"(?:%u[0-9a-fA-F]{4}){4,}", # Unicode shellcode patterns - often used to bypass filters
"\b(?:0x[0-9a-fA-F]{8,})\b", # Memory addresses and long hex values
"\b(?:mov|push|pop|call|jmp|ret)\s+(?:eax|ebx|ecx|edx|esi|edi)\b" # Common assembly instruction patterns found in shellcode
)
Whitelist = @(
# .NET runtime and interop patterns
'System\.Runtime\.InteropServices',
'DllImport\(.+?\)',
'Marshal\.(Copy|Alloc)',
# Legitimate PowerShell API calls
'Add-Type',
'VirtualAlloc',
'CreateThread',
'WaitForSingleObject',
# Common programming language constructs
'(?:public|private|protected)\s+(?:class|struct|enum)',
'(?:function|def|sub)\s+\w+\s*\(',
# Hash values and crypto patterns
'[A-Fa-f0-9]{32,}', # MD5/SHA hashes
'0x[0-9A-Fa-f]+(?:\s*,\s*0x[0-9A-Fa-f]+){0,3}', # Small hex arrays
# CSS color codes and styling
'#[0-9A-Fa-f]{6}\b',
'rgba?\([^)]+\)',
# Memory allocation and pointer operations
'(?:malloc|free|new|delete)\s*\([^)]*\)',
'(?:memcpy|memset|memmove)\s*\([^)]*\)'
)
},
@{
Type = "Injection Functions"
Patterns = @(
# PowerShell Commands
"Invoke-Expression",
"iex",
"Invoke-Command",
"icm",
"Start-Process",
"Invoke-Item",
"New-Object",
"Add-Type",
# Windows API
"CreateRemoteThread",
"OpenProcess",
"VirtualAllocEx",
"WriteProcessMemory",
"ReadProcessMemory",
"GetProcAddress",
"LoadLibraryA",
"LoadLibraryW",
"VirtualFreeEx",
"CreateProcessA",
"CreateProcessW",
"VirtualProtect",
"HeapCreate",
"HeapAlloc",
# Reflection
"System\.Reflection",
"Assembly\.Load",
"[RuntimeType]",
# Script Execution
"\$ExecutionContext",
"ScriptBlock",
"ExpandString",
"-EncodedCommand",
"-ExecutionPolicy",
"-NoProfile"
)
Whitelist = @(
# Development Paths
"vendor/",
"node_modules/",
"packages/",
"bin/",
"obj/",
"dist/",
"build/",
"test/",
# Code Comments
"//.*",
"#.*",
"/\*[\s\S]*?\*/",
"'''[\s\S]*?'''",
'"""[\s\S]*?"""',
# Documentation
"@param",
"@return",
"TODO:",
"FIXME:",
# Function References
'function\s+reference',
# Generated Code
'composer',
'autoload',
'vendor',
'generated'
)
},
@{
Type = "Webshell Functions"
Patterns = @(
# PowerShell Command Execution
"\bInvoke-Expression\s*\(|\bIEX\s*\(",
"\bInvoke-Command\s*\(",
"\bStart-Process\s*\(",
"\bInvoke-WmiMethod\s*\(",
"\bInvoke-RestMethod\s*\(",
"\bInvoke-WebRequest\s*\(",
# Code Execution & Reflection
"\bAdd-Type\s*\(",
"\b[System\.Reflection\.Assembly]::(Load|LoadFrom|LoadFile)",
"\bCreateInstance\s*\(",
"\bScriptBlock\.Create\s*\(",
"\bGet-WmiObject\s*\(",
"\bGet-CimInstance\s*\(",
# Network Operations
"\bNew-Object\s+(Net\.WebClient|System\.Net\.Sockets\.(TCP|UDP)Client)",
"\bDownload(String|File)\s*\(",
"\bTest-(Net)?Connection\s*\(",
"\bWNet\.",
"\bNet\s+(User|LocalGroup)\s*\(",
# File Operations
"\b(Set|Add)-Content\s*\(",
"\bOut-File\s*\(",
"\bNew-Item\s*\(",
"\b(Copy|Move|Remove)-Item\s*\(",
"\b(Compress|Expand)-Archive\s*\(",
# Registry & Service Operations
"\b(Get|Set|New)-ItemProperty\s*\(",
"\b(New|Start)-Service\s*\(",
# Encoding/Decoding
"\b[Convert]::(From|To)Base64String\s*\(",
"\b[System\.Text\.Encoding]::(UTF8|ASCII|Unicode)\.GetString\s*\(",
"\bSystem\.Convert\.",
# Remote Management
"\bEnable-PSRemoting\s*\(",
"\b(New|Connect)-PSSession\s*\(",
"\bSet-PSSessionConfiguration\s*\(",
# Process & Job Management
"\bStart-Job\s*\(",
"\bRegister-(ScheduledJob|WmiEvent)\s*\(",
"\bInvoke-AsWorkflow\s*\(",
# Additional Potential Risks
"\bReflection\.Emit\.",
"\bRunspace\.",
"\bPowerShell\.(Create|AddScript)\s*\(",
"\bWMISecurity\.",
"\bGet-Process\s*\(",
"\bStop-Process\s*\(",
"\bEnvironment\.\w+\.",
"\bSystem\.Diagnostics\.",
"\bSystem\.IO\."
)
Whitelist = @(
# Comments & Documentation
'^\s*#.*$',
'^\s*<#[\s\S]*?#>',
# Safe Paths & Files
'\\(Tests|UnitTests|Examples|Samples)\\',
'\.(config|psd1|psm1|tests\.ps1)$',
'(Program\s+Files|Windows\\System32|WindowsPowerShell)',
# Development Context
'(test|mock|unittest|example|debug|log)',
'(visual\s+studio|vscode|rider|jetbrains|resharper)',
# Safe Functions & Modules
'function\s+(Get|Test|ConvertTo|ConvertFrom)-',
'Microsoft\.PowerShell\.',
'System\.Management\.Automation\.',
'(Import|Export)-Module',
'Using\s+module',
# Logging & Output
'Write-(Host|Output|Verbose|Debug)',
# Parameters & Error Handling
'-(ErrorAction|WarningAction|InformationAction|Verbose|Debug)',
# Testing Frameworks
'(Pester|Should|Context|Describe|Mock)',
# Build & Configuration
'(build|deploy|install)\.ps1$',
'(config|build|generate|nuget|package)',
# Module Structure
'module',
'function\s+\w+',
'class\s+\w+',
'interface\s+\w+',
# Common Safe Operations
'PSModulePath',
'powershell\s+core',
'Export-ModuleMember',
# Additional Safe Context Indicators
'license',
'readme',
'documentation',
'compliance',
'automation',
'monitoring',
'reporting'
)
},
@{
Type = "Hardcoded Secrets"
Patterns = @(
# Credentials
'(?i)(password|passwd|pwd)\s*[:=]\s*["`''][^"`'']+["`'']',
'(?i)(username|user|uid)\s*[:=]\s*["`''][^"`'']+["`'']',
'(?i)(api[_-]?key|access[_-]?key|secret[_-]?key)\s*[:=]\s*["`''][^"`'']+["`'']',
# Tokens & Auth
'(?i)(token|jwt|bearer)\s*[:=]\s*["`''][^"`'']+["`'']',
'(?i)(auth|oauth)\s*[:=]\s*["`''][^"`'']+["`'']',
# Connection Strings
'(?i)(connection[_-]?string|conn[_-]?str)\s*[:=]\s*["`''][^"`'']+["`'']',
'(?i)(jdbc:|mongodb://|redis://|mysql://)[^"`'']+["`'']',
# Private Keys
'(?i)BEGIN\s+(RSA|DSA|EC|OPENSSH)\s+PRIVATE\s+KEY',
'(?i)(private[_-]?key|secret[_-]?key)\s*[:=]\s*["`''][^"`'']+["`'']',
# Backdoors
'(?i)(admin|root|administrator|superuser)\s*[:=]\s*["`''][^"`'']+["`'']',
'(?i)uid\s*[=:]\s*["`'']?0["`'']?',
'(?i)(shell_exec|system|passthru|exec|eval)\s*\(',
'(?i)(cmd|command|powershell|bash|sh)\.exe',
'(?i)Runtime\.getRuntime\(\)\.exec\('
)
Whitelist = @(
# Java
'@Value\(["`''].*["`'']\)',
'@PropertySource',
'application\.properties',
'application\.yml',
# .NET
'appsettings\.json',
'web\.config',
'IConfiguration',
'IOptions<',
'UserSecrets',
# Python
'os\.environ\.get',
'config\.get',
'settings\.py',
# Node.js
'process\.env',
'\.env',
'config\.js',
# Go
'os\.Getenv',
'viper\.Get',
# Test Files
'[._](test|spec|mock)',
'(test|spec)/.*\.',
# Example Files
'\.(example|sample|template)',
'examples?/',
# Documentation
'(readme|docs?|documentation)',
'[._]md$',
# Secret Management
'vault\.',
'secrets[_-]manager',
'key[_-]vault',
'encrypted[_-]'
)
},
@{
Type = "Webshell via File Upload"
Patterns = @(
# Common file upload methods and libraries across multiple languages (C#, PHP, Java, etc.)
# Detects patterns for methods involved in file uploading
# C#/.NET specific file upload methods
'HttpPostedFile(Base)?', # C# HttpPostedFile (common in ASP.NET MVC)
'File\.SaveAs\(', # C# specific method for saving files to disk
'System\.Web\.HttpPostedFileBase', # HttpPostedFileBase (ASP.NET MVC)
# PHP specific file upload functions
'move_uploaded_file\(', # PHP file upload move
'file_put_contents\(', # PHP function to write files
'$_FILES', # PHP global variable used in file upload handling
# General file upload patterns
'enctype=["'']multipart/form-data["'']', # HTML form attribute for file uploads
'\.UploadFile\(', # Common method to handle file uploads
'upload\(', # Generic upload method detection
# Common patterns for handling file uploads
'(?i)(upload|process)(File|Upload)', # Variants for method names that handle file upload
'(?i)handle(File|FileUpload)', # Generic file handling functions in upload contexts
# Detects potentially insecure ways of handling file uploads
'move_uploaded_file\(', # PHP file move upload, commonly insecure
'file_put_contents\(', # Insecure file writes (PHP, other languages)
# Broader patterns that may indicate insecure file handling
'(?i)(upload|process)(File|Upload|Handler)', # Broad terms for insecure upload methods
'file\s*(?:\+|=)\s*new\s*File\(', # Detects file creation and manipulation
'(?i)unsafeFileUpload', # Detects a possible insecure file upload flag
'(?i)allow\W*File\W*Upload', # Detects potentially insecure file upload flags in code
'Request\.Files', # Detects file handling in web frameworks
'file\s*=\s*new\s*File\(' # Detects file object creation related to uploads
)
# Whitelist patterns to avoid false positives
Whitelist = @(
# Secure checks for file uploads
'ValidateFile(Type|Extension|Size)', # Secure validation for file type, extension, and size
'Check(File)?(Mime)?Type', # Checking mime types for validation
'Sanitize(FileName)?', # Sanitizing file names for security
'Scan(ForMalware)?', # Scanning files for malware before upload
# Secure storage and handling of files
'SecureFile(Storage|Provider)', # Storing files securely
'Safe(File)?Upload', # Safe file upload methods
# Test and testing-related patterns
'(?:Unit|Integration)Test(Case)?', # Unit or integration test cases (to avoid test patterns)
'FileUpload(Test)?', # Specific tests for file upload
# Known secure frameworks/libraries
'Microsoft\.AspNetCore\.Http', # ASP.NET Core HttpFile handling
'System\.Web\.HttpPostedFile', # ASP.NET legacy file upload handling
'Apache(Commons)?FileUpload', # Apache Commons FileUpload (secure)
'secureFileUploadMethod', # Explicit secure upload methods (whitelist)
'FileUploadWithSanitization', # Uploads with added sanitization and checks
'SecureFileWrite' # Files being written securely
)
}
)
function Get-FileHash {
param (
[string]$filePath
)
try {
$hash = Get-FileHash -Path $filePath -Algorithm SHA256
return $hash.Hash
}
catch {
return "Could not calculate hash"
}
}
function Get-FileMetadata {
param (
[string]$filePath
)
try {
$file = Get-Item $filePath
return @{
CreationTime = $file.CreationTime
LastWriteTime = $file.LastWriteTime
LastAccessTime = $file.LastAccessTime
Size = $file.Length
Extension = $file.Extension
Hash = Get-FileHash -filePath $filePath
}
}
catch {
return $null
}
}
function Test-ValidContext {
param (
[string]$content,
[string]$match,
[array]$whitelistPatterns
)
# Get surrounding context (expanded to 100 characters before and after)
$contextStart = [Math]::Max(0, $content.IndexOf($match) - 100)
$contextLength = [Math]::Min(200, $content.Length - $contextStart)
$surroundingContext = $content.Substring($contextStart, $contextLength)
# Check if surrounding context matches excluded patterns
if (Is-ExcludedContext -text $surroundingContext) {
return $false
}
# Check whitelist patterns
foreach ($whitePattern in $whitelistPatterns) {
$escapedPattern = [regex]::Escape($whitePattern)
$escapedMatch = [regex]::Escape($match)
if ($content -match "(?s)$escapedPattern.*?\b$escapedMatch\b") {
return $false
}
}
return $true
}
function Is-ExcludedContext {
param (
[string]$text
)
return $text -match $excludedRegex
}
# Initialize scan statistics
$scanStats = @{
StartTime = Get-Date
TotalFiles = 0
ScannedFiles = 0
MatchesFound = 0
ErrorCount = 0
Errors = @()
}
# Create progress bar
$progressParams = @{
Activity = "Scanning files for suspicious patterns"
Status = "Initializing..."
PercentComplete = 0
}
# Output the project folder path
Write-Host "Starting scan in path: '$projectFolderPath'" -ForegroundColor Green
Write-Host "Initializing scan..." -ForegroundColor Yellow
# Define a central list of excluded patterns
$excludedPatterns = @(
'composer', 'autoload', 'vendor', 'cache', 'generated',
'test', 'mock', 'example', 'package', 'namespace',
'class', 'function',
'^\s*//', # Single-line comments starting with //
'\*', # Block comments
'^\s*\*', # Line starting with * (often used in block comments)
'\s*if\s*\(', # If conditions
'\s*=\s*\(', # Assignment operations
'return\s+' # Return statements
)
# Convert to a regex pattern (case-insensitive)
$excludedRegex = "(?i)(" + ($excludedPatterns -join '|') + ")"
# Get and cache the list of files to scan
$files = Get-ChildItem -Path $projectFolderPath -Recurse -Include *.java, *.php, *.cs, *.html, *.js, *.py, *.go, *.cpp, *.c, *.h, *.hpp
# Set total files count
$scanStats.TotalFiles = $files.Count
# Process files using the cached list
$files | ForEach-Object {
$filePath = $_.FullName
$scanStats.ScannedFiles++
# Update progress bar
$progressParams.Status = "Scanning $($_.Name)"
$progressParams.PercentComplete = ($scanStats.ScannedFiles / $scanStats.TotalFiles * 100)
Write-Progress @progressParams
try {
if (Is-ExcludedContext -text $filePath) {
return
}
$fileLines = Get-Content -Path $filePath -ErrorAction Stop
$fileContent = $fileLines -join "`n"
$metadata = Get-FileMetadata -filePath $filePath
foreach ($patternGroup in $patterns) {
$vulnerabilityType = $patternGroup.Type
foreach ($pattern in $patternGroup.Patterns) {
# Use regex to find all matches with their positions
$regex = [regex]$pattern
$matches = $regex.Matches($fileContent)
foreach ($match in $matches) {
if (Test-ValidContext -content $fileContent -match $match.Value -whitelistPatterns $patternGroup.Whitelist) {
# Calculate the correct line number
$matchPosition = $match.Index
$lineNumber = ($fileContent.Substring(0, $matchPosition) -split '\r?\n').Count
$contextStart = [Math]::Max(0, $match.Index - 100)
$contextLength = [Math]::Min(200, $fileContent.Length - $contextStart)
$context = $fileContent.Substring($contextStart, $contextLength)
if (-not (Is-ExcludedContext -text $context)) {
$matchObject = [PSCustomObject]@{
FilePath = $filePath
FileName = Split-Path $filePath -Leaf
VulnerabilityType = $vulnerabilityType
Pattern = $pattern
LineNumber = $lineNumber # Accurate line number calculation
LineText = $fileLines[$lineNumber - 1].Trim() # Get the actual line text
Context = $context
Metadata = $metadata
MatchValue = $match.Value
Severity = switch ($vulnerabilityType) {
"Shellcode Patterns" { "High" }
"Injection Functions" { "High" }
"Webshell Functions" { "Critical" }
"Math Pattern" { "Medium" }
"Webshell via File Upload" { "Low" }
default { "Low" }
}
RiskScore = switch ($vulnerabilityType) {
"Shellcode Patterns" { 8 }
"Injection Functions" { 9 }
"Webshell Functions" { 10 }
"Math Pattern" { 6 }
"Webshell via File Upload" { 4 }
default { 4 }
}
}
$allMatches += $matchObject
$scanStats.MatchesFound++
}
}
}
}
}
}
catch {
$scanStats.ErrorCount++
$scanStats.Errors += [PSCustomObject]@{
FilePath = $filePath
Error = $_.Exception.Message
}
Write-Warning "Error processing file $filePath : $($_.Exception.Message)"
}
}
# Complete the progress bar
Write-Progress @progressParams -Completed
# Calculate scan statistics
$scanStats.EndTime = Get-Date
$scanStats.Duration = $scanStats.EndTime - $scanStats.StartTime
$scanStats.MatchesByType = $allMatches | Group-Object -Property VulnerabilityType |
Select-Object @{N='Type';E={$_.Name}}, @{N='Count';E={$_.Count}}
# Create summary report
$summary = @"
Scan Summary Report
==================
Scan Start Time: $($scanStats.StartTime)
Scan End Time: $($scanStats.EndTime)
Duration: $($scanStats.Duration.ToString())
Total Files: $($scanStats.TotalFiles)
Files Scanned: $($scanStats.ScannedFiles)
Matches Found: $($scanStats.MatchesFound)
Errors Encountered: $($scanStats.ErrorCount)
Matches by Vulnerability Type:
$($scanStats.MatchesByType | ForEach-Object { "$($_.Type): $($_.Count)" })
High Risk Findings (Score >= 8):
$($allMatches | Where-Object { $_.RiskScore -ge 8 } |
Select-Object -First 10 |
ForEach-Object { "- [$($_.Severity)] $($_.FilePath): $($_.VulnerabilityType)" })
"@
# Generate detailed HTML report
$htmlReport = @"
<!DOCTYPE html>
<html>
<head>
<title>Security Scan Report - $folderName</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.header { background-color: #f5f5f5; padding: 20px; border-radius: 5px; }
.summary { margin: 20px 0; }
.findings { margin: 20px 0; }
.finding { border: 1px solid #ddd; padding: 10px; margin: 10px 0; border-radius: 5px; }
.high { border-left: 5px solid #CC0000; }
.medium { border-left: 5px solid #ffbb33; }
.low { border-left: 5px solid #00C851; }
.critical { border-left: 5px solid #9932CC; }
pre { background-color: #f8f9fa; padding: 10px; border-radius: 3px; overflow-x: auto; }
.stats { display: flex; justify-content: space-between; flex-wrap: wrap; }
.stat-box { background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin: 5px; min-width: 200px; }
</style>
</head>
<body>
<div class="header">
<h1>Security Scan Report</h1>
<p>Project: $folderName</p>
<p>Scan Date: $($scanStats.StartTime)</p>
</div>
<div class="summary">
<h2>Scan Statistics</h2>
<div class="stats">
<div class="stat-box">
<h3>Total Files</h3>
<p>$($scanStats.TotalFiles)</p>
</div>
<div class="stat-box">
<h3>Files Scanned</h3>
<p>$($scanStats.ScannedFiles)</p>
</div>
<div class="stat-box">
<h3>Matches Found</h3>
<p>$($scanStats.MatchesFound)</p>
</div>
<div class="stat-box">
<h3>Errors</h3>
<p>$($scanStats.ErrorCount)</p>
</div>
</div>
</div>
<div class="findings">
<h2>Findings</h2>
$(
$allMatches | Sort-Object -Property RiskScore -Descending | ForEach-Object {
@"
<div class="finding $($_.Severity.ToLower())">
<h3>[$($_.Severity)] $($_.VulnerabilityType)</h3>
<p><strong>File:</strong> $($_.FilePath)</p>
<p><strong>Risk Score:</strong> $($_.RiskScore)/10</p>
<p><strong>Pattern:</strong> $($_.Pattern)</p>
<p><strong>Line Number:</strong> $($_.LineNumber)</p>
<p><strong>Context:</strong></p>
<pre>$($_.Context)</pre>
</div>
"@
}
)
</div>
<div class="errors" style="margin-top: 20px;">
<h2>Errors</h2>
$(
if ($scanStats.Errors.Count -gt 0) {
$scanStats.Errors | ForEach-Object {
"<div class='finding low'><p><strong>File:</strong> $($_.FilePath)</p><p><strong>Error:</strong> $($_.Error)</p></div>"
}
} else {
"<p>No errors encountered during scan.</p>"
}
)
</div>
</body>
</html>
"@
# Save results
$summary | Out-File -FilePath $outputFilePath
$htmlReport | Out-File -FilePath "$folderName-report.html"
$allMatches | ConvertTo-Json -Depth 10 | Out-File -FilePath $jsonOutputPath
$allMatches | Export-Csv -Path $csvOutputPath -NoTypeInformation
# Display completion message with color coding
Write-Host "`nScan completed!" -ForegroundColor Green
Write-Host "Summary saved to: $outputFilePath" -ForegroundColor Yellow
Write-Host "HTML report saved to: $folderName-report.html" -ForegroundColor Yellow
Write-Host "JSON results saved to: $jsonOutputPath" -ForegroundColor Yellow
Write-Host "CSV results saved to: $csvOutputPath" -ForegroundColor Yellow
# Display quick summary
Write-Host "`nQuick Summary:" -ForegroundColor Cyan
Write-Host "=============" -ForegroundColor Cyan
Write-Host "Total files scanned: $($scanStats.ScannedFiles)" -ForegroundColor White
Write-Host "Total matches found: $($scanStats.MatchesFound)" -ForegroundColor White
Write-Host "Errors encountered: $($scanStats.ErrorCount)" -ForegroundColor White
Write-Host "`nHigh Risk Findings:" -ForegroundColor Red
$allMatches | Where-Object { $_.RiskScore -ge 8 } |
Select-Object -First 5 |
ForEach-Object {
Write-Host "- [$($_.Severity)] $($_.FilePath): $($_.VulnerabilityType)" -ForegroundColor Red
}
# Create email report if findings exceed threshold
if ($scanStats.MatchesFound -gt 0) {
$emailBody = @"
Security Scan Alert - High Risk Findings Detected
Project: $folderName
Scan Date: $($scanStats.StartTime)
Total Findings: $($scanStats.MatchesFound)
High Risk Findings:
$($allMatches | Where-Object { $_.RiskScore -ge 8 } |
Select-Object -First 10 |
ForEach-Object { "- [$($_.Severity)] $($_.FilePath): $($_.VulnerabilityType)" })
Please review the attached HTML report for complete details.
"@
# Save email content for later use
$emailBody | Out-File -FilePath "$folderName-email-alert.txt"
}
# Return scan results object
return @{
Stats = $scanStats
Matches = $allMatches
Summary = $summary
ReportPath = "$folderName-report.html"
}