-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity_test2.ps1
More file actions
7584 lines (6521 loc) · 369 KB
/
security_test2.ps1
File metadata and controls
7584 lines (6521 loc) · 369 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ============================================================================
# ADVANCED SECURITY TESTING SUITE v2.0 (Enhanced & Production-Ready)
# ============================================================================
# LEGAL WARNING:
# - Only run against systems you own or have written authorization to test
# - Unauthorized security testing may be illegal in your jurisdiction
# - The authors assume no liability for misuse of this tool
# ============================================================================
param(
[Parameter(Mandatory=$false)]
[string]$site = "https://example.com",
# renamed from $verbose to avoid conflict with PowerShell's built-in -Verbose common parameter
[Parameter(Mandatory=$false)]
[switch]$dverbose = $false,
[Parameter(Mandatory=$false)]
[switch]$quick = $false,
[Parameter(Mandatory=$false)]
[switch]$skipSlow = $false,
[Parameter(Mandatory=$false)]
[string]$outputDir = ".",
[Parameter(Mandatory=$false)]
[int]$timeout = 10,
[Parameter(Mandatory=$false)]
[string]$userAgent = "SecurityScanner/2.0 (Authorized Testing)",
[Parameter(Mandatory=$false)]
[switch]$htmlReport = $false,
[Parameter(Mandatory=$false)]
[switch]$noColor = $false,
# NEW PROFESSIONAL PARAMETERS
[Parameter(Mandatory=$false)]
[string]$ConfirmAuthorization = "",
[Parameter(Mandatory=$false)]
[ValidateSet("Passive", "Aggressive")]
[string]$Mode = "Passive",
[Parameter(Mandatory=$false)]
[int]$MaxRequests = 1000,
[Parameter(Mandatory=$false)]
[switch]$ForceExternal = $false,
[Parameter(Mandatory=$false)]
[string]$BaselineReport = "",
# AUTHENTICATED TESTING PARAMETERS
[Parameter(Mandatory=$false)]
[string]$Username = "",
[Parameter(Mandatory=$false)]
[string]$Password = "",
[Parameter(Mandatory=$false)]
[string]$LoginUrl = "",
[Parameter(Mandatory=$false)]
[string]$LoginEndpoint = "/login",
[Parameter(Mandatory=$false)]
[string]$TestUser = "test@example.com",
[Parameter(Mandatory=$false)]
[Alias("AuthCookie")]
[string]$SessionCookie = "",
[Parameter(Mandatory=$false)]
[string]$AuthUserId = "",
[Parameter(Mandatory=$false)]
[hashtable]$AuthHeaders = @{}
)
# ----------------------------------------------------------------------------
# CONFIGURATION & GLOBALS
# ----------------------------------------------------------------------------
$ErrorActionPreference = "SilentlyContinue"
$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$scanId = [guid]::NewGuid().ToString().Substring(0,8)
# Output files
$logFile = Join-Path $outputDir "security_scan_${timestamp}_${scanId}.log"
$jsonReport = Join-Path $outputDir "security_scan_${timestamp}_${scanId}.json"
$htmlReportPath = Join-Path $outputDir "security_scan_${timestamp}_${scanId}.html"
$csvReport = Join-Path $outputDir "security_scan_${timestamp}_${scanId}.csv"
# Issue tracking with enhanced metadata
$script:issues = @{
Critical = @()
High = @()
Medium = @()
Low = @()
Info = @()
}
# CWE/OWASP Mapping Database
$script:cweMappings = @{
"XSS" = @{ CWE = "CWE-79"; OWASP = "A03:2021 - Injection" }
"SQLi" = @{ CWE = "CWE-89"; OWASP = "A03:2021 - Injection" }
"CommandInjection" = @{ CWE = "CWE-78"; OWASP = "A03:2021 - Injection" }
"PathTraversal" = @{ CWE = "CWE-22"; OWASP = "A03:2021 - Injection" }
"CSRF" = @{ CWE = "CWE-352"; OWASP = "A01:2021 - Broken Access Control" }
"Clickjacking" = @{ CWE = "CWE-1021"; OWASP = "A01:2021 - Broken Access Control" }
"OpenRedirect" = @{ CWE = "CWE-601"; OWASP = "A01:2021 - Broken Access Control" }
"CORS" = @{ CWE = "CWE-942"; OWASP = "A01:2021 - Broken Access Control" }
"InfoDisclosure" = @{ CWE = "CWE-200"; OWASP = "A02:2021 - Cryptographic Failures" }
"WeakSession" = @{ CWE = "CWE-384"; OWASP = "A07:2021 - Identification and Authentication Failures" }
"BruteForce" = @{ CWE = "CWE-307"; OWASP = "A07:2021 - Identification and Authentication Failures" }
"SensitiveDataExposure" = @{ CWE = "CWE-200"; OWASP = "A02:2021 - Cryptographic Failures" }
"SecurityMisconfiguration" = @{ CWE = "CWE-16"; OWASP = "A05:2021 - Security Misconfiguration" }
"CachePoisoning" = @{ CWE = "CWE-444"; OWASP = "A05:2021 - Security Misconfiguration" }
"HPP" = @{ CWE = "CWE-235"; OWASP = "A03:2021 - Injection" }
"DoS" = @{ CWE = "CWE-400"; OWASP = "A05:2021 - Security Misconfiguration" }
}
$script:testResults = @{}
$script:scanStats = @{
StartTime = Get-Date
EndTime = $null
Duration = $null
TestsRun = 0
TestsPassed = 0
TestsFailed = 0
RequestsMade = 0
BytesReceived = 0
}
# Authentication state management
$script:authState = @{
IsAuthenticated = $false
SessionCookies = @{}
AuthHeaders = @{}
Username = ""
LoginTimestamp = $null
CSRFToken = ""
CSRFTokenName = ""
}
# ----------------------------------------------------------------------------
# ENHANCED OUTPUT FUNCTIONS
# ----------------------------------------------------------------------------
function Write-ColorOutput {
param($message, $color = "White", $level = "INFO")
if ($noColor) {
$prefix = "[$level]"
Write-Host "$prefix $message"
return
}
$colorMap = @{
"SUCCESS" = "Green"
"DANGER" = "Red"
"WARNING" = "Yellow"
"INFO" = "Cyan"
"DEBUG" = "Gray"
}
$fgColor = if ($colorMap.ContainsKey($level)) { $colorMap[$level] } else { $color }
$prefix = switch ($level) {
"SUCCESS" { "[OK]" }
"DANGER" { "[X]" }
"WARNING" { "[!]" }
"INFO" { "[i]" }
"DEBUG" { "[D]" }
default { "[$level]" }
}
Write-Host "$prefix $message" -ForegroundColor $fgColor
}
function Write-Success { param($m) Write-ColorOutput $m -level "SUCCESS" }
function Write-Danger { param($m) Write-ColorOutput $m -level "DANGER" }
function Write-Warning { param($m) Write-ColorOutput $m -level "WARNING" }
function Write-Info { param($m) Write-ColorOutput $m -level "INFO" }
function Write-Debug { param($m) if ($dverbose) { Write-ColorOutput $m -level "DEBUG" } }
function Write-Section {
param($title, $testNumber = "")
$separator = "=" * 70
Write-Host ""
Write-Host $separator -ForegroundColor Magenta
if ($testNumber) {
Write-Host "== TEST $testNumber : $title" -ForegroundColor Magenta
} else {
Write-Host "== $title" -ForegroundColor Magenta
}
Write-Host $separator -ForegroundColor Magenta
Write-Host ""
}
function Write-Log {
param($message, $level = "INFO")
$timestampNow = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestampNow] [$level] $message"
$logEntry | Out-File -Append -FilePath $logFile -Encoding UTF8
if ($dverbose) { Write-Debug $message }
}
function Write-Progress-Custom {
param($activity, $status, $percentComplete)
Write-Progress -Activity $activity -Status $status -PercentComplete $percentComplete
}
# ----------------------------------------------------------------------------
# UTILITY: URL encode / decode without System.Web.HttpUtility
# ----------------------------------------------------------------------------
function Encode-Url {
param(
[Parameter(Mandatory = $true)]
[string]$Text
)
return [System.Uri]::EscapeDataString($Text)
}
function Decode-Url {
param(
[Parameter(Mandatory = $true)]
[string]$Text
)
return [System.Uri]::UnescapeDataString($Text)
}
# ----------------------------------------------------------------------------
# ISSUE MANAGEMENT
# ----------------------------------------------------------------------------
function Add-Issue {
param(
[Parameter(Mandatory=$true)]
[ValidateSet("Critical","High","Medium","Low","Info")]
[string]$severity,
[Parameter(Mandatory=$true)]
[string]$title,
[Parameter(Mandatory=$true)]
[string]$description,
[string]$url = "",
[string]$remediation = "",
[string]$cve = "",
[string]$cvss = "",
[hashtable]$evidence = @{ },
# Professional security testing metadata
[string]$cweId = "",
[string]$owaspCategory = "",
[ValidateSet("Transport","Session","Authentication","Authorization","Input Validation","Browser Hardening","Information Disclosure","Cryptography","Configuration","Access Control","Business Logic")]
[string]$category = "",
[ValidateSet("High","Medium","Low")]
[string]$confidence = "Medium",
[string]$issueType = "",
# Executive-level reporting fields
[string]$whyItMatters = "",
[string]$suggestedFix = ""
)
# Auto-map CWE and OWASP if issueType is provided
if ($issueType -and $script:cweMappings.ContainsKey($issueType)) {
if (-not $cweId) { $cweId = $script:cweMappings[$issueType].CWE }
if (-not $owaspCategory) { $owaspCategory = $script:cweMappings[$issueType].OWASP }
}
# Use remediation as suggestedFix if suggestedFix not provided
if (-not $suggestedFix -and $remediation) {
$suggestedFix = $remediation
}
$issue = [PSCustomObject]@{
Severity = $severity
Title = $title
Description = $description
URL = $url
Remediation = $remediation
WhyItMatters = $whyItMatters
SuggestedFix = $suggestedFix
CVE = $cve
CVSS = $cvss
Evidence = $evidence
Timestamp = Get-Date
TestNumber = $script:currentTestNumber
CWE = $cweId
OWASPCategory = $owaspCategory
Category = $category
Confidence = $confidence
IssueType = $issueType
}
$script:issues[$severity] += $issue
Write-Log "[$severity] $title - $description" $severity.ToUpper()
switch ($severity) {
"Critical" { Write-Danger "CRITICAL: $title" }
"High" { Write-Danger "HIGH: $title" }
"Medium" { Write-Warning "MEDIUM: $title" }
"Low" { Write-Warning "LOW: $title" }
"Info" { Write-Info "INFO: $title" }
}
}
# ----------------------------------------------------------------------------
# HTTP REQUEST WRAPPER WITH AUTHENTICATION SUPPORT
# ----------------------------------------------------------------------------
function Invoke-SafeWebRequest {
param(
[string]$uri,
[string]$method = "GET",
[hashtable]$headers,
[int]$timeoutSec = $timeout,
[bool]$allowRedirect = $true,
[string]$body = $null,
[bool]$returnRaw = $false,
[bool]$useAuth = $true
)
# Initialize headers if not provided
if (-not $headers) {
$headers = @{}
}
$script:scanStats.RequestsMade++
try {
# Merge authentication headers if authenticated
if ($useAuth -and $script:authState.IsAuthenticated) {
foreach ($key in $script:authState.AuthHeaders.Keys) {
if (-not $headers.ContainsKey($key)) {
$headers[$key] = $script:authState.AuthHeaders[$key]
}
}
}
$params = @{
Uri = $uri
Method = $method
Headers = $headers
TimeoutSec = $timeoutSec
UserAgent = $userAgent
ErrorAction = 'Stop'
}
# Add session cookies if authenticated
if ($useAuth -and $script:authState.IsAuthenticated -and $script:authState.SessionCookies.Count -gt 0) {
$cookieContainer = New-Object System.Net.CookieContainer
$uriObj = [System.Uri]$uri
foreach ($cookieName in $script:authState.SessionCookies.Keys) {
$cookie = New-Object System.Net.Cookie
$cookie.Name = $cookieName
$cookie.Value = $script:authState.SessionCookies[$cookieName]
$cookie.Domain = $uriObj.Host
$cookieContainer.Add($cookie)
}
$params.WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$params.WebSession.Cookies = $cookieContainer
}
if (-not $allowRedirect) {
$params.MaximumRedirection = 0
}
if ($body) {
$params.Body = $body
}
$response = Invoke-WebRequest @params
$script:scanStats.BytesReceived += $response.Content.Length
if ($returnRaw) {
return $response
}
return @{
Success = $true
StatusCode = $response.StatusCode
Headers = $response.Headers
Content = $response.Content
Response = $response
}
}
catch {
$statusCode = $null
if ($_.Exception.Response) {
$statusCode = [int]$_.Exception.Response.StatusCode
}
return @{
Success = $false
StatusCode = $statusCode
Error = $_.Exception.Message
Exception = $_
}
}
}
# ============================================================================
# AUTHENTICATION & SESSION MANAGEMENT
# ============================================================================
function Initialize-Authentication {
<#
.SYNOPSIS
Initializes authenticated session for scanning while logged in
#>
Write-Info "Checking authentication configuration..."
# Method 1: Direct session cookie provided
if ($SessionCookie) {
Write-Info "Using provided session cookie for authentication"
# Parse cookie string (format: "name=value" or "name1=value1; name2=value2")
$cookiePairs = $SessionCookie -split ';'
foreach ($pair in $cookiePairs) {
$parts = $pair.Trim() -split '=', 2
if ($parts.Count -eq 2) {
$script:authState.SessionCookies[$parts[0].Trim()] = $parts[1].Trim()
}
}
$script:authState.IsAuthenticated = $true
Write-Success "Session cookie configured"
return $true
}
# Method 2: Username/Password login
if ($Username -and $Password) {
if (-not $LoginUrl) {
$LoginUrl = "$site/login"
}
Write-Info "Attempting form-based authentication to: $LoginUrl"
try {
# First, get the login page to extract CSRF token
$loginPageResult = Invoke-SafeWebRequest -uri $LoginUrl -method "GET" -useAuth $false
if ($loginPageResult.Success) {
$loginHtml = $loginPageResult.Content
# Try to detect CSRF token
$csrfToken = ""
$csrfTokenName = ""
$tokenPatterns = @{
'_csrf' = '<input[^>]*name=["' + "'" + ']_csrf["' + "'" + '][^>]*value=["' + "'" + '](.*?)["' + "'" + ']'
'csrf_token' = '<input[^>]*name=["' + "'" + ']csrf_token["' + "'" + '][^>]*value=["' + "'" + '](.*?)["' + "'" + ']'
'csrfmiddlewaretoken' = '<input[^>]*name=["' + "'" + ']csrfmiddlewaretoken["' + "'" + '][^>]*value=["' + "'" + '](.*?)["' + "'" + ']'
'__RequestVerificationToken' = '<input[^>]*name=["' + "'" + ']__RequestVerificationToken["' + "'" + '][^>]*value=["' + "'" + '](.*?)["' + "'" + ']'
'authenticity_token' = '<input[^>]*name=["' + "'" + ']authenticity_token["' + "'" + '][^>]*value=["' + "'" + '](.*?)["' + "'" + ']'
}
foreach ($tokenName in $tokenPatterns.Keys) {
if ($loginHtml -match $tokenPatterns[$tokenName]) {
$csrfToken = $Matches[1]
$csrfTokenName = $tokenName
Write-Info ("Detected CSRF token: " + $csrfTokenName)
break
}
}
# Build login payload
$loginData = @{
username = $Username
password = $Password
}
# Add CSRF token if found
if ($csrfToken) {
$loginData[$csrfTokenName] = $csrfToken
$script:authState.CSRFToken = $csrfToken
$script:authState.CSRFTokenName = $csrfTokenName
}
# Convert to form-encoded string
$formBody = ($loginData.GetEnumerator() | ForEach-Object {
"$([System.Uri]::EscapeDataString($_.Key))=$([System.Uri]::EscapeDataString($_.Value))"
}) -join '&'
# Attempt login
$loginHeaders = @{
'Content-Type' = 'application/x-www-form-urlencoded'
}
$loginResult = Invoke-SafeWebRequest -uri $LoginUrl -method "POST" -body $formBody -headers $loginHeaders -useAuth $false
if ($loginResult.Success -or $loginResult.StatusCode -in @(302, 303)) {
# Extract session cookies from response
if ($loginResult.Response.Headers['Set-Cookie']) {
$cookies = $loginResult.Response.Headers['Set-Cookie']
foreach ($cookie in $cookies) {
$cookieParts = $cookie -split ';'
$mainPart = $cookieParts[0] -split '=', 2
if ($mainPart.Count -eq 2) {
$script:authState.SessionCookies[$mainPart[0].Trim()] = $mainPart[1].Trim()
}
}
}
$script:authState.IsAuthenticated = $true
$script:authState.Username = $Username
$script:authState.LoginTimestamp = Get-Date
Write-Success "Successfully authenticated as: $Username"
Write-Info "Session cookies captured: $($script:authState.SessionCookies.Keys -join ', ')"
return $true
}
else {
Write-Warning "Login failed with status: $($loginResult.StatusCode)"
Write-Warning "Login may have failed - continuing unauthenticated"
return $false
}
}
}
catch {
Write-Warning "Authentication failed: $_"
return $false
}
}
# Method 3: Custom auth headers
if ($AuthHeaders.Count -gt 0) {
Write-Info "Using custom authentication headers"
$script:authState.AuthHeaders = $AuthHeaders
$script:authState.IsAuthenticated = $true
Write-Success "Custom auth headers configured"
return $true
}
# No authentication configured
Write-Info "No authentication credentials provided - running unauthenticated scan"
return $false
}
function Test-AuthenticationStatus {
<#
.SYNOPSIS
Verifies that authentication is still valid
#>
if (-not $script:authState.IsAuthenticated) {
return $false
}
try {
# Try to access a page that should require authentication
# Use the site root or a common authenticated endpoint
$testUrl = "$site/account"
$result = Invoke-SafeWebRequest -uri $testUrl -method "GET" -useAuth $true
# If we get 401/403, session expired
if ($result.StatusCode -in @(401, 403)) {
Write-Warning "Authentication session appears to have expired"
$script:authState.IsAuthenticated = $false
return $false
}
return $true
}
catch {
return $true # Assume OK if can't verify
}
}
# ----------------------------------------------------------------------------
# ENHANCED TEST TRACKING
# ----------------------------------------------------------------------------
function Start-SecurityTest {
param($testName, $testNumber)
$script:currentTestNumber = $testNumber
$script:currentTestName = $testName
$script:testResults[$testName] = @{
Number = $testNumber
StartTime = Get-Date
Status = "Running"
IssuesFound = 0
}
$script:scanStats.TestsRun++
Write-Section $testName $testNumber
}
function Complete-SecurityTest {
param([string]$status = "Completed")
$test = $script:testResults[$script:currentTestName]
$test.EndTime = Get-Date
$test.Duration = ($test.EndTime - $test.StartTime).TotalSeconds
$test.Status = $status
if ($status -eq "Completed") {
$script:scanStats.TestsPassed++
} else {
$script:scanStats.TestsFailed++
}
}
# ============================================================================
# GRACEFUL TEST EXECUTION WRAPPER
# ============================================================================
function Invoke-TestWithFallback {
<#
.SYNOPSIS
Executes security test with graceful error handling
.DESCRIPTION
Wraps test execution in try-catch to prevent single test failures from aborting entire scan
#>
param(
[scriptblock]$TestFunction,
[string]$TestName
)
try {
& $TestFunction
}
catch {
$errorDetails = @{
Message = $_.Exception.Message
Type = $_.Exception.GetType().FullName
Line = $_.InvocationInfo.ScriptLineNumber
Position = $_.InvocationInfo.PositionMessage
StackTrace = $_.ScriptStackTrace
}
Write-Danger "═══════════════════════════════════════════════════════"
Write-Danger " TEST FAILED: $TestName"
Write-Danger "═══════════════════════════════════════════════════════"
Write-Danger "Error: $($errorDetails.Message)"
Write-Warning "Type: $($errorDetails.Type)"
if ($errorDetails.Line) {
Write-Info "Location: Line $($errorDetails.Line)"
}
Write-Danger "═══════════════════════════════════════════════════════"
Write-Log "Test $TestName failed with error: $($errorDetails.Message)" "ERROR"
Write-Log "Error Type: $($errorDetails.Type)" "ERROR"
Write-Log "Stack trace: $($errorDetails.StackTrace)" "DEBUG"
# Log as test issue with full context
Add-Issue -severity "Info" `
-title "Test Execution Error: $TestName" `
-description "This test encountered an unhandled exception and could not complete. Error: $($errorDetails.Message)" `
-remediation "Review test implementation or target site configuration. Check scan logs for full stack trace." `
-whyItMatters "Test failures may indicate: 1) Scanner bugs, 2) Unexpected target behavior, 3) Network issues, 4) Edge cases not handled. This is a scanner reliability issue, not necessarily a target vulnerability." `
-suggestedFix "1. Check scan logs for full error details. 2. Verify target site is accessible and stable. 3. Re-run scan to confirm if error is transient. 4. Report persistent errors to scanner maintainer." `
-category "Configuration" `
-issueType "TestExecutionError" `
-confidence "High" `
-evidence $errorDetails
# Mark test as failed but continue
if ($script:currentTestName) {
Complete-SecurityTest -status "Failed"
}
Write-Warning "Continuing with remaining tests..."
Write-Host ""
}
}
# ============================================================================
# TEST 0: PRE-SCAN SAFETY & SCOPE VALIDATION
# ============================================================================
function Test-ScopeAndSafety {
Start-SecurityTest "Scope and Safety Validation" "0"
$result = @{
Name = "ScopeAndSafety"
Status = "Failed"
Duration = 0
Issues = @()
Evidence = @{}
Metrics = @{
ScopeValidated = $false
Mode = $Mode
MaxRequests = $MaxRequests
TesterIdentity = $env:USERNAME
Timestamp = Get-Date
TargetDomain = ""
}
}
try {
# Extract domain from site URL
$uri = [System.Uri]$site
$targetDomain = $uri.Host
$result.Metrics.TargetDomain = $targetDomain
Write-Info "Target Domain: $targetDomain"
Write-Info "Mode: $Mode"
Write-Info "Max Requests: $MaxRequests"
Write-Info "Tester: $($env:USERNAME)"
# CRITICAL: Authorization confirmation check
if ([string]::IsNullOrWhiteSpace($ConfirmAuthorization)) {
Write-Danger "ABORT: No authorization confirmation provided!"
Write-Warning "You MUST provide -ConfirmAuthorization 'I am authorized to test $targetDomain'"
Add-Issue -severity "Critical" `
-title "Authorization Not Confirmed" `
-description "No explicit authorization confirmation was provided. Security testing without authorization may be illegal." `
-remediation "Provide -ConfirmAuthorization parameter with explicit confirmation." `
-issueType "SecurityMisconfiguration" `
-confidence "High"
$result.Status = "Aborted"
return $result
}
# Validate authorization matches target
if ($ConfirmAuthorization -notmatch [regex]::Escape($targetDomain)) {
Write-Danger "ABORT: Authorization confirmation does not match target domain!"
Write-Warning "Confirmation: '$ConfirmAuthorization'"
Write-Warning "Target: '$targetDomain'"
Add-Issue -severity "Critical" `
-title "Authorization Mismatch" `
-description "The authorization confirmation does not match the target domain being tested." `
-remediation "Ensure authorization confirmation explicitly mentions '$targetDomain'." `
-issueType "SecurityMisconfiguration" `
-confidence "High"
$result.Status = "Aborted"
return $result
}
# Check for dangerous wildcard targets in Aggressive mode
if ($Mode -eq "Aggressive" -and -not $ForceExternal) {
$dangerousPatterns = @('*.gov', '*.mil', '*.edu', '*.bank', '*.com', '*.org', '*.net')
foreach ($pattern in $dangerousPatterns) {
if ($targetDomain -like $pattern -or $targetDomain -match '\*') {
Write-Danger "ABORT: Wildcard/broad target detected in Aggressive mode without -ForceExternal!"
Write-Warning "Target: '$targetDomain'"
Add-Issue -severity "Critical" `
-title "Unsafe Target Scope" `
-description "Wildcard or extremely broad target detected in Aggressive mode. This could affect unintended systems." `
-remediation "Use specific domain names or add -ForceExternal if you're certain." `
-issueType "SecurityMisconfiguration" `
-confidence "High"
$result.Status = "Aborted"
return $result
}
}
}
# Warn about aggressive mode
if ($Mode -eq "Aggressive") {
Write-Warning "AGGRESSIVE MODE ENABLED - Higher request volume and more intrusive tests will run"
Write-Warning "Ensure target system can handle increased load"
Start-Sleep -Seconds 2
}
# Check request budget
if ($MaxRequests -lt 100) {
Write-Warning "MaxRequests is very low ($MaxRequests). Some tests may be skipped."
}
# All checks passed
Write-Success "Scope validation PASSED"
Write-Success "Authorization confirmed for: $targetDomain"
Write-Success "Mode: $Mode | Max Requests: $MaxRequests"
$result.Metrics.ScopeValidated = $true
$result.Status = "Completed"
Add-Issue -severity "Info" `
-title "Scope Validation Successful" `
-description "Pre-scan safety checks passed. Target: $targetDomain, Mode: $Mode, MaxRequests: $MaxRequests, Tester: $($env:USERNAME)" `
-remediation "N/A - Informational" `
-confidence "High"
}
catch {
Write-Danger "Error during scope validation: $_"
$result.Status = "Failed"
$result.Issues += $_
}
Complete-SecurityTest $result.Status
return $result
}
# ----------------------------------------------------------------------------
# BANNER & INITIALIZATION
# ----------------------------------------------------------------------------
function Show-Banner {
$banner = @"
╔═══════════════════════════════════════════════════════════════╗
║ ║
║ ADVANCED SECURITY TESTING SUITE v2.0 ║
║ Comprehensive Web Application Security Scanner ║
║ ║
╚═══════════════════════════════════════════════════════════════╝
"@
Write-Host $banner -ForegroundColor Cyan
}
function Initialize-Scan {
Show-Banner
Write-Info "Initializing security scan..."
Write-Info "Target: $site"
Write-Info "Scan ID: $scanId"
Write-Info "Output Directory: $outputDir"
Write-Info "Quick Mode: $quick"
Write-Info "Skip Slow Tests: $skipSlow"
Write-Host ""
if (-not (Test-Path $outputDir)) {
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
}
Write-Log "==================================================================="
Write-Log "SECURITY SCAN INITIALIZED"
Write-Log "Target: $site"
Write-Log "Scan ID: $scanId"
Write-Log "Timestamp: $(Get-Date)"
Write-Log "User: $env:USERNAME@$env:COMPUTERNAME"
Write-Log "==================================================================="
try {
$uri = [System.Uri]$site
if ($uri.Scheme -notin @("http", "https")) {
throw "Invalid URL scheme. Must be http or https"
}
}
catch {
Write-Danger "Invalid target URL: $_"
exit 1
}
}
# ============================================================================
# TEST 1: APPLICATION DISCOVERY & FINGERPRINTING
# ============================================================================
function Test-AppDiscovery {
Start-SecurityTest "Application Discovery and Fingerprinting" "01"
$result = @{
Name = "AppDiscovery"
Status = "Completed"
Duration = 0
Issues = @()
Evidence = @{}
Metrics = @{
StackComponents = @()
ServerInfo = @{}
DNSInfo = @{}
CloudProvider = "Unknown"
}
}
try {
# ========== DNS & HOSTING INFO ==========
Write-Info "Phase 1: DNS & Hosting Analysis..."
try {
$uri = [System.Uri]$site
$hostname = $uri.Host
# Resolve A/AAAA records
$dnsEntries = [System.Net.Dns]::GetHostAddresses($hostname)
$ipList = $dnsEntries | ForEach-Object { $_.IPAddressToString }
Write-Info "Resolved IP addresses: $($ipList -join ', ')"
$result.Metrics.DNSInfo = @{
Hostname = $hostname
IPs = $ipList
IPCount = $ipList.Count
HasIPv6 = ($dnsEntries | Where-Object { $_.AddressFamily -eq 'InterNetworkV6' }).Count -gt 0
}
if ($ipList.Count -gt 1) {
Write-Info "Multiple IPs detected - likely using load balancer or CDN"
$result.Metrics.DNSInfo.LoadBalancerHint = $true
}
# Cloud provider detection (heuristic based on IP ranges and hostnames)
$cloudHints = @()
foreach ($ip in $ipList) {
# AWS ranges: check for common AWS patterns
if ($ip -match '^(54\.|52\.|3\.)' -or $hostname -match 'amazonaws|aws') {
$cloudHints += "AWS"
}
# Azure ranges
if ($ip -match '^(13\.|20\.|40\.|52\.|104\.)' -or $hostname -match 'azure|microsoft') {
$cloudHints += "Azure"
}
# GCP ranges
if ($ip -match '^(34\.|35\.)' -or $hostname -match 'googleapis|google') {
$cloudHints += "GCP"
}
# Cloudflare
if ($ip -match '^(104\.1[6-9]\.|104\.2[0-9]\.|104\.3[0-1]\.|172\.64\.|172\.65\.|172\.66\.|172\.67\.)' -or $hostname -match 'cloudflare') {
$cloudHints += "Cloudflare"
}
}
if ($cloudHints.Count -gt 0) {
$provider = $cloudHints | Select-Object -Unique -First 1
$result.Metrics.CloudProvider = $provider
Write-Info "Detected cloud provider: $provider"
Add-Issue -severity "Info" `
-title "Cloud Provider Detected: $provider" `
-description "Application appears to be hosted on $provider infrastructure" `
-remediation "N/A - Informational" `
-issueType "InfoDisclosure" `
-confidence "Medium"
}
}
catch {
Write-Warning "DNS analysis failed: $_"
}
# ========== HTTP BANNER & STACK FINGERPRINT ==========
Write-Info "Phase 2: HTTP Banner & Stack Fingerprinting..."
$httpResult = Invoke-SafeWebRequest -uri $site -method "GET"
if (-not $httpResult.Success) {
$errorMsg = $httpResult.Error
$isRateLimited = $errorMsg -match '429' -or $errorMsg -match 'Too Many Requests' -or $errorMsg -match 'rate.?limit'
if ($isRateLimited) {
Write-Danger "Target enforced rate limiting: $errorMsg"
Add-Issue -severity "Critical" `
-title "Target Enforcing Aggressive Rate Limiting" `
-description "HTTP 429 (Too Many Requests) received during initial connection. Target has aggressive WAF/rate limiting that prevents security assessment. Error: $errorMsg" `
-remediation "Re-run tests with: 1) Lower request volume (-Quick flag), 2) Authenticated session (-SessionCookie) to bypass guest rate limits, 3) Longer delays between tests, 4) Whitelist scanner IP with site administrator" `
-whyItMatters "Rate limiting prevents comprehensive security assessment. This scanner could not complete fingerprinting or vulnerability detection due to throttling. For production assessments, work with site administrators to whitelist your IP or provide authenticated credentials." `
-suggestedFix "Contact site administrator to: (A) Whitelist scanner IP address, (B) Provide test account credentials for authenticated scanning, (C) Temporarily relax rate limits during assessment window" `
-category "Operational" `
-issueType "RateLimiting" `
-confidence "High" `
-evidence @{
HTTPStatus = "429"
ErrorMessage = $errorMsg
Recommendation = "Use -SessionCookie with authenticated session"
}
} else {
Write-Danger "Target unreachable: $errorMsg"
Add-Issue -severity "Critical" `
-title "Target Unreachable" `
-description "Cannot establish HTTP connection: $errorMsg" `
-remediation "Verify target URL and network connectivity. Check: 1) URL is correct and includes protocol (https://), 2) Target server is online, 3) Firewall allows outbound connections, 4) DNS resolution is working" `
-confidence "High"
}
Complete-SecurityTest "Failed"
return $result
}
Write-Success "Target reachable (Status: $($httpResult.StatusCode))"
# Server header analysis
$server = $httpResult.Headers['Server']
if ($server) {
$result.Metrics.ServerInfo.Header = $server
$result.Metrics.ServerInfo.HasVersionNumber = ($server -match '[\d\.]+')
Write-Warning "Server header exposed: $server"
Add-Issue -severity "Medium" `
-title "Server Header Disclosure" `
-description "Server header reveals technology: $server" `
-remediation "Remove or obfuscate Server header to prevent targeted attacks" `
-evidence @{ Header = "Server"; Value = $server } `
-issueType "InfoDisclosure" `
-confidence "High"
if ($server -match '[\d\.]+') {
Write-Warning "Version information leaked in Server header"
Add-Issue -severity "Medium" `
-title "Server Version Disclosure" `
-description "Detailed version exposed: $server. This aids attackers in identifying known vulnerabilities." `
-remediation "Remove version numbers from Server header" `
-issueType "InfoDisclosure" `
-confidence "High"
}
}
# Technology disclosure headers
$techHeaders = @{
'X-Powered-By' = @{ Severity = 'Medium'; Desc = 'Backend technology' }
'X-AspNet-Version' = @{ Severity = 'Medium'; Desc = 'ASP.NET version' }
'X-AspNetMvc-Version' = @{ Severity = 'Medium'; Desc = 'ASP.NET MVC version' }