Repository navigation
Expand file tree
/
Copy pathTest-JvmSecurity.ps1
More file actions
6957 lines (6144 loc) · 450 KB
/
Copy pathTest-JvmSecurity.ps1
File metadata and controls
6957 lines (6144 loc) · 450 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
# Java Version Manager
# Copyright (C) 2026 DiamTek / Alexéy Shishkin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
<#
Synopsis:
- Automated Security & Adversarial Test Suite for DiamTek Java Version Manager (JVM).
================================================================================
Targets:
- jvm.bat (CLI input sanitization, delayed expansion, reparse points)
- install.ps1 / uninstall.ps1 (REG_EXPAND_SZ, non-destructive junction unbind)
- scripts/bump-version.ps1 (manifest validation, dry-run immutability)
- packages/** (Chocolatey, Scoop, Winget manifest integrity)
Usage:
pwsh -NoProfile -ExecutionPolicy Bypass -File .\tests\Test-JvmSecurity.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\tests\Test-JvmSecurity.ps1
================================================================================
#>
[CmdletBinding()]
param(
[switch]$Detailed,
[Alias('Tag', 'Category')]
[string]$Suite = '',
[Alias('Name', 'Pattern')]
[string]$Filter = ''
)
$ErrorActionPreference = 'Stop'
$RequestedSuite = $Suite
$RequestedFilter = $Filter
# UI Colors
$ESC = [char]27
$cReset = "$ESC[0m"
$cBold = "$ESC[1m"
$cCyan = "$ESC[36m"
$cGreen = "$ESC[32m"
$cYellow = "$ESC[33m"
$cRed = "$ESC[31m"
$cGray = "$ESC[90m"
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
if (-not $ScriptDir) { $ScriptDir = (Get-Location).Path }
$RepoRoot = if (Test-Path (Join-Path $ScriptDir "jvm.bat")) {
$ScriptDir
} elseif (Test-Path (Join-Path $ScriptDir "..\jvm.bat")) {
(Resolve-Path "$ScriptDir\..").Path
} else {
$ScriptDir
}
$JvmBat = Join-Path $RepoRoot "jvm.bat"
if (-not (Test-Path $JvmBat)) {
Write-Host "${cRed}[FATAL] Could not locate jvm.bat at: $JvmBat${cReset}"
exit 1
}
# Ensure critical Windows system directories and process caller identity are configured
$sys32 = [System.Environment]::GetFolderPath('System')
$sysWin = [System.Environment]::GetFolderPath('Windows')
$sysPaths = @($sys32, $sysWin, (Join-Path $sys32 'Wbem'), (Join-Path $sys32 'WindowsPowerShell\v1.0'))
foreach ($sp in $sysPaths) {
if ($sp -and (Test-Path -LiteralPath $sp) -and ($env:PATH -notlike "*$sp*")) {
$env:PATH = "$sp;$env:PATH"
}
}
$env:JVM_CALLER_PID = $PID
# Ensure user-writable TEMP directory (prevents C:\Windows\TEMP permission issues)
$userTemp = Join-Path $env:USERPROFILE "AppData\Local\Temp"
if (Test-Path -LiteralPath $userTemp) {
$env:TEMP = $userTemp
$env:TMP = $userTemp
}
$TestResults = [System.Collections.Generic.List[PSObject]]::new()
$GlobalPassed = 0
$GlobalFailed = 0
$GlobalSkipped = 0
$HasPassedSuite2 = $false
$RunnerStopwatch = [System.Diagnostics.Stopwatch]::StartNew()
# Canonical 16-Suite Catalog
$SuiteTracker = [ordered]@{
'SUITE 1' = [PSCustomObject]@{ Id = 'SUITE 1'; Number = 1; Name = 'Suite 1: Adversarial & Fuzzing Defense'; Tag = 'Adversarial'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 2' = [PSCustomObject]@{ Id = 'SUITE 2'; Number = 2; Name = 'Suite 2: Registry & Env Boundaries'; Tag = 'Registry'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 3' = [PSCustomObject]@{ Id = 'SUITE 3'; Number = 3; Name = 'Suite 3: Symlink & Junction Lifecycle'; Tag = 'ReparsePoint'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 4' = [PSCustomObject]@{ Id = 'SUITE 4'; Number = 4; Name = 'Suite 4: Package Manifest Integrity'; Tag = 'Manifest'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 5' = [PSCustomObject]@{ Id = 'SUITE 5'; Number = 5; Name = 'Suite 5: Concurrency & Reparse Resilience'; Tag = 'Concurrency'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 6' = [PSCustomObject]@{ Id = 'SUITE 6'; Number = 6; Name = 'Suite 6: Corrupt Registry & PATH Resilience'; Tag = 'Registry'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 7' = [PSCustomObject]@{ Id = 'SUITE 7'; Number = 7; Name = 'Suite 7: Uninstallation Safety & Markers'; Tag = 'Uninstall'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 8' = [PSCustomObject]@{ Id = 'SUITE 8'; Number = 8; Name = 'Suite 8: Windows Terminal JSONC Parsing'; Tag = 'TerminalJSON'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 9' = [PSCustomObject]@{ Id = 'SUITE 9'; Number = 9; Name = 'Suite 9: Advanced Cache & Content-Addressed Storage'; Tag = 'Cache'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 10' = [PSCustomObject]@{ Id = 'SUITE 10'; Number = 10; Name = 'Suite 10: Multi-Candidate Ecosystem Toolchains'; Tag = 'Ecosystem'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 11' = [PSCustomObject]@{ Id = 'SUITE 11'; Number = 11; Name = 'Suite 11: Transactional Recovery & Journal Logging'; Tag = 'Transaction'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 12' = [PSCustomObject]@{ Id = 'SUITE 12'; Number = 12; Name = 'Suite 12: Enterprise Networking & Machine Policy Enforcement'; Tag = 'EnterprisePolicy'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 13' = [PSCustomObject]@{ Id = 'SUITE 13'; Number = 13; Name = 'Suite 13: Advanced Lockfile Lifecycle, Freezing & Signatures'; Tag = 'LockfileLifecycle'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 14' = [PSCustomObject]@{ Id = 'SUITE 14'; Number = 14; Name = 'Suite 14: Unified Status, Ergonomics & Multi-Shell Cross-Compatibility'; Tag = 'ShellErgonomics'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 15' = [PSCustomObject]@{ Id = 'SUITE 15'; Number = 15; Name = 'Suite 15: Adversarial Robustness, Fuzzing & Mutation Resilience'; Tag = 'AdversarialMutation'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
'SUITE 16' = [PSCustomObject]@{ Id = 'SUITE 16'; Number = 16; Name = 'Suite 16: Next-Gen Portability, Profiles, Snapshots & Toolchain Distros'; Tag = 'Portability'; Passed = 0; Failed = 0; Skipped = 0; Total = 0; ElapsedMs = 0L }
}
# Canonical CWE Vulnerability Catalog (Sorted Numerically - 41 CWEs)
$CweCatalog = [ordered]@{
'CWE-20' = [PSCustomObject]@{ Id = 'CWE-20'; Number = 20; Short = 'Improper Input & Config Validation' }
'CWE-22' = [PSCustomObject]@{ Id = 'CWE-22'; Number = 22; Short = 'Path Traversal & ZipSlip' }
'CWE-41' = [PSCustomObject]@{ Id = 'CWE-41'; Number = 41; Short = 'Win32 Canonicalization Bypass' }
'CWE-59' = [PSCustomObject]@{ Id = 'CWE-59'; Number = 59; Short = 'Symlink & Junction Safety' }
'CWE-66' = [PSCustomObject]@{ Id = 'CWE-66'; Number = 66; Short = 'DOS Device & NTFS ADS Abuse' }
'CWE-73' = [PSCustomObject]@{ Id = 'CWE-73'; Number = 73; Short = 'Env & System Root Protection' }
'CWE-74' = [PSCustomObject]@{ Id = 'CWE-74'; Number = 74; Short = 'XML Attribute & Template Injection' }
'CWE-78' = [PSCustomObject]@{ Id = 'CWE-78'; Number = 78; Short = 'OS Command & Shell Injection' }
'CWE-88' = [PSCustomObject]@{ Id = 'CWE-88'; Number = 88; Short = 'Argument & Flag Injection' }
'CWE-94' = [PSCustomObject]@{ Id = 'CWE-94'; Number = 94; Short = 'Batch set /a Expression Evaluation' }
'CWE-155' = [PSCustomObject]@{ Id = 'CWE-155'; Number = 155; Short = 'Wildcard Expansion Injection' }
'CWE-184' = [PSCustomObject]@{ Id = 'CWE-184'; Number = 184; Short = 'Incomplete List-Based Input Sanitization' }
'CWE-209' = [PSCustomObject]@{ Id = 'CWE-209'; Number = 209; Short = 'Error Message Stack-Trace Suppression' }
'CWE-250' = [PSCustomObject]@{ Id = 'CWE-250'; Number = 250; Short = 'Privilege Boundary Isolation' }
'CWE-252' = [PSCustomObject]@{ Id = 'CWE-252'; Number = 252; Short = 'Unchecked Return Value & Exit Propagation' }
'CWE-276' = [PSCustomObject]@{ Id = 'CWE-276'; Number = 276; Short = 'Strict Directory DACL Isolation' }
'CWE-295' = [PSCustomObject]@{ Id = 'CWE-295'; Number = 295; Short = 'TLS 1.2 / 1.3 Protocol Enforcement' }
'CWE-319' = [PSCustomObject]@{ Id = 'CWE-319'; Number = 319; Short = 'Strict HTTPS Scheme Enforcement' }
'CWE-330' = [PSCustomObject]@{ Id = 'CWE-330'; Number = 330; Short = 'CSPRNG Temp Filename Entropy' }
'CWE-345' = [PSCustomObject]@{ Id = 'CWE-345'; Number = 345; Short = 'Downgrade & Authenticity Defense' }
'CWE-354' = [PSCustomObject]@{ Id = 'CWE-354'; Number = 354; Short = 'Checksum Manifest Format Validation' }
'CWE-362' = [PSCustomObject]@{ Id = 'CWE-362'; Number = 362; Short = 'Race Condition & Concurrent State' }
'CWE-367' = [PSCustomObject]@{ Id = 'CWE-367'; Number = 367; Short = 'Atomic Staged Profile/Config Writes' }
'CWE-377' = [PSCustomObject]@{ Id = 'CWE-377'; Number = 377; Short = 'Insecure Temp File & ACL Lock' }
'CWE-390' = [PSCustomObject]@{ Id = 'CWE-390'; Number = 390; Short = 'Error Condition Action & Logging' }
'CWE-400' = [PSCustomObject]@{ Id = 'CWE-400'; Number = 400; Short = 'Hang & Parser Resilience' }
'CWE-409' = [PSCustomObject]@{ Id = 'CWE-409'; Number = 409; Short = 'Zip Bomb & Decompression Bounds' }
'CWE-426' = [PSCustomObject]@{ Id = 'CWE-426'; Number = 426; Short = 'Untrusted Search Path / Planting' }
'CWE-427' = [PSCustomObject]@{ Id = 'CWE-427'; Number = 427; Short = 'Uncontrolled PATH Hijack Defense' }
'CWE-428' = [PSCustomObject]@{ Id = 'CWE-428'; Number = 428; Short = 'Quoted UninstallString & TargetPath' }
'CWE-459' = [PSCustomObject]@{ Id = 'CWE-459'; Number = 459; Short = 'Failure-Path Handle & Temp Cleanup' }
'CWE-460' = [PSCustomObject]@{ Id = 'CWE-460'; Number = 460; Short = 'Exception Cleanup & Atomic Rollback' }
'CWE-494' = [PSCustomObject]@{ Id = 'CWE-494'; Number = 494; Short = 'Supply Chain & Hash Integrity' }
'CWE-532' = [PSCustomObject]@{ Id = 'CWE-532'; Number = 532; Short = 'Sensitive Registry Backup Isolation' }
'CWE-601' = [PSCustomObject]@{ Id = 'CWE-601'; Number = 601; Short = 'Open Redirect & Host Allowlisting' }
'CWE-611' = [PSCustomObject]@{ Id = 'CWE-611'; Number = 611; Short = 'XML External Entity (XXE) Defense' }
'CWE-674' = [PSCustomObject]@{ Id = 'CWE-674'; Number = 674; Short = 'Uncontrolled Recursion & Cyclic Loops' }
'CWE-754' = [PSCustomObject]@{ Id = 'CWE-754'; Number = 754; Short = 'Exceptional Condition Check' }
'CWE-755' = [PSCustomObject]@{ Id = 'CWE-755'; Number = 755; Short = 'Exceptional Condition Handling' }
'CWE-798' = [PSCustomObject]@{ Id = 'CWE-798'; Number = 798; Short = 'Hardcoded Credentials Defense' }
'CWE-918' = [PSCustomObject]@{ Id = 'CWE-918'; Number = 918; Short = 'SSRF & Vendor Domain Allowlisting' }
}
$cweDescriptions = @{}
foreach ($k in $CweCatalog.Keys) { $cweDescriptions[$k] = $CweCatalog[$k].Short }
function Resolve-TestCweMetadata {
param([string]$RawSuite, [string]$TestName)
if ($TestName -match '\((CWE-\d+)' -and $script:CweCatalog.Contains($matches[1])) {
return $script:CweCatalog[$matches[1]]
}
$cweKey = switch -Regex ($TestName) {
'Stack-Trace|ScriptStackTrace|PositionMessage|sanitizes catch' { 'CWE-209'; break }
'Return Value|Exit Propagation|LASTEXITCODE|errorlevel' { 'CWE-252'; break }
'empty catch|CatchClauseAst|Write-Verbose|Error Condition Action' { 'CWE-390'; break }
'Atomic Rollback|PREV_JUNCTION_TARGET|\.jvm_bak_|\.old' { 'CWE-460'; break }
'Incomplete List-Based|Denylist-Based|incomplete sanitization' { 'CWE-184'; break }
'Race Condition|Concurrent State|atomic commit|staging config' { 'CWE-362'; break }
'Uncontrolled Recursion|Cyclic|cyclic|infinite traversal' { 'CWE-674'; break }
'Exceptional Condition Check|wixExitCode' { 'CWE-754'; break }
'Exceptional Condition Handling|fail-closed|ConstrainedLanguage' { 'CWE-755'; break }
'ZipSlip|Path Traversal|traversal|sibling prefix|boundary enforcement|target allowlisting' { 'CWE-22'; break }
'Trailing dot|Trailing space|trailing dots|trailing spaces|single dot|Reserved keyword' { 'CWE-41'; break }
'DOS reserved|Alternative Data Stream|ADS' { 'CWE-66'; break }
'Leading hyphen|leading-hyphen|--vendor|invalid value rejection' { 'CWE-88'; break }
'Asterisk wildcard|Question mark wildcard' { 'CWE-155'; break }
'Pinned System Binaries|SystemRoot environment saturation|Base64 UTF-16LE' { 'CWE-426'; break }
'junction|Reparse|Remove-DirectorySafely|active development repository' { 'CWE-59'; break }
'ACL verification|Parallel temp script' { 'CWE-377'; break }
'REG_EXPAND_SZ|REG_SZ|Protected system roots|lacking JVM installation|Oracle javapath' { 'CWE-73'; break }
'SendMessageTimeout|Extreme PATH|JSONC|Corrupt non-JSON|NO_COLOR' { 'CWE-400'; break }
'SHA|checksum|nuspec|Scoop|Winget|synchronization|DryRun|UTF-8|Get-DeterministicGuid|WIX1103' { 'CWE-494'; break }
default { 'CWE-78' }
}
return $script:CweCatalog[$cweKey]
}
function Resolve-TestCwe {
param([string]$TestName, [string]$RawSuite = '')
return Resolve-TestCweMetadata -RawSuite $RawSuite -TestName $TestName
}
function Resolve-TestCweAllIds {
param([string]$TestName, [PSCustomObject]$PrimaryCweMeta)
$ids = [System.Collections.Generic.List[string]]::new()
foreach ($m in [regex]::Matches($TestName, 'CWE-\d+')) {
if ($script:CweCatalog.Contains($m.Value) -and (-not $ids.Contains($m.Value))) {
$ids.Add($m.Value)
}
}
if ($PrimaryCweMeta -and (-not $ids.Contains($PrimaryCweMeta.Id))) {
$ids.Add($PrimaryCweMeta.Id)
}
return @($ids)
}
$RegisteredTests = [System.Collections.Generic.List[PSCustomObject]]::new()
function Resolve-CanonicalSuite {
param([string]$RawSuite, [string]$TestName = '')
if ($RawSuite -eq 'ReparsePoint') {
$script:HasPassedSuite2 = $true
}
if ($RawSuite -eq 'Cache' -or $TestName -match '(?i)(Content-Addressed|CAS sha256|jvm cache|Cache bundle import|Resumable Downloads|Smart Retry with Exponential Backoff|Configurable Download Mirrors)') {
return $script:SuiteTracker['SUITE 9']
}
if ($RawSuite -eq 'Ecosystem' -or $TestName -match '(?i)(ResolveLatestEcosystemCandidate|EcoPerformCheck|UninstallCandidate and :InstallCandidate|Interactive ecosystem version prompt|Remote Search Engine|Remote search candidate|jvm compare|Version comparison specification|Toolchain Conflict Detection|Smart Contextual Execution|\.jvm\.toml|Exact Semantic Build)') {
return $script:SuiteTracker['SUITE 10']
}
if ($RawSuite -in @('Transaction', 'AtomicOperations') -or $TestName -match '(?i)(Transactional installations|transaction recovery|Transaction journal rollback|Interrupted activation pre-state|Self-Update Rollback & History)') {
return $script:SuiteTracker['SUITE 11']
}
$suiteKey = switch ($RawSuite) {
'Adversarial' { 'SUITE 1' }
'Registry' { if ($script:HasPassedSuite2) { 'SUITE 6' } else { 'SUITE 2' } }
'ReparsePoint' { 'SUITE 3' }
'Manifest' { 'SUITE 4' }
'PackageIntegrity' { 'SUITE 4' }
'SupplyChain' { 'SUITE 4' }
'Reparse' { 'SUITE 5' }
'Concurrency' { 'SUITE 5' }
'Uninstall' { 'SUITE 7' }
'UninstallSafety' { 'SUITE 7' }
'TerminalJSON' { 'SUITE 8' }
'EnterprisePolicy' { 'SUITE 12' }
'LockfileLifecycle' { 'SUITE 13' }
'ShellErgonomics' { 'SUITE 14' }
'AdversarialMutation' { 'SUITE 15' }
'Portability' { 'SUITE 16' }
default {
$dynKey = "SUITE_DYN_$RawSuite"
if (-not $script:SuiteTracker.Contains($dynKey)) {
$nextNum = $script:SuiteTracker.Count + 1
$script:SuiteTracker[$dynKey] = [PSCustomObject]@{
Id = "SUITE $nextNum"
Number = $nextNum
Name = "Suite ${nextNum}: $RawSuite"
Tag = $RawSuite
Passed = 0
Failed = 0
Skipped = 0
Total = 0
ElapsedMs = 0L
}
}
$dynKey
}
}
return $script:SuiteTracker[$suiteKey]
}
function Test-RunnerFilterMatch {
param(
[PSCustomObject]$SuiteEntry,
[PSCustomObject]$CweMeta,
[string]$RawSuite,
[string]$TestName
)
if (-not [string]::IsNullOrWhiteSpace($script:RequestedSuite)) {
$q = $script:RequestedSuite.Trim()
$suiteCandidates = @(
$RawSuite,
$SuiteEntry.Tag,
$SuiteEntry.Id,
"Suite$($SuiteEntry.Number)",
"$($SuiteEntry.Number)",
$SuiteEntry.Name
)
$matchedSuite = $false
foreach ($cand in $suiteCandidates) {
if ($cand -like "*$q*" -or $cand -match $q) {
$matchedSuite = $true
break
}
}
if (-not $matchedSuite) { return $false }
}
if (-not [string]::IsNullOrWhiteSpace($script:RequestedFilter)) {
$f = $script:RequestedFilter.Trim()
$matchedFilter = ($TestName -like "*$f*") -or ($RawSuite -like "*$f*") -or ($SuiteEntry.Name -like "*$f*") -or ($CweMeta.Id -like "*$f*") -or ($CweMeta.Short -like "*$f*")
if (-not $matchedFilter) {
try {
$matchedFilter = ($TestName -match $f) -or ($RawSuite -match $f) -or ($SuiteEntry.Name -match $f) -or ($CweMeta.Id -match $f) -or ($CweMeta.Short -match $f)
} catch {
$matchedFilter = $false
}
}
if (-not $matchedFilter) { return $false }
}
return $true
}
function Run-TestCase {
param(
[string]$Suite,
[string]$Name,
[scriptblock]$TestLogic
)
$suiteEntry = Resolve-CanonicalSuite -RawSuite $Suite -TestName $Name
$cweMeta = Resolve-TestCweMetadata -RawSuite $Suite -TestName $Name
$allCweIds = Resolve-TestCweAllIds -TestName $Name -PrimaryCweMeta $cweMeta
$script:RegisteredTests.Add([PSCustomObject]@{
SuiteEntry = $suiteEntry
RawSuite = $Suite
Name = $Name
CweMeta = $cweMeta
AllCweIds = $allCweIds
TestLogic = $TestLogic
})
}
function Invoke-RegisteredTestSuites {
foreach ($suiteKey in $script:SuiteTracker.Keys) {
$suiteObj = $script:SuiteTracker[$suiteKey]
$suiteTests = @($script:RegisteredTests | Where-Object { $_.SuiteEntry.Id -eq $suiteObj.Id })
if ($suiteTests.Count -eq 0) { continue }
$matchingTests = [System.Collections.Generic.List[PSCustomObject]]::new()
foreach ($t in $suiteTests) {
if (Test-RunnerFilterMatch -SuiteEntry $t.SuiteEntry -CweMeta $t.CweMeta -RawSuite $t.RawSuite -TestName $t.Name) {
$matchingTests.Add($t)
} else {
$script:GlobalSkipped++
$t.SuiteEntry.Skipped++
}
}
if ($matchingTests.Count -eq 0) { continue }
$headerTitle = $suiteObj.Name -replace '^Suite\s+\d+:\s*', ''
Write-Host ""
Write-Host "$cBold[$($suiteObj.Id)] $headerTitle$cReset"
foreach ($test in $matchingTests) {
$suiteEntry = $test.SuiteEntry
$cweMeta = $test.CweMeta
$allCweIds = $test.AllCweIds
$Name = $test.Name
$Suite = $test.RawSuite
$TestLogic = $test.TestLogic
$suiteEntry.Total++
$cweBadge = "${cCyan}[$($cweMeta.Id)]${cReset}"
$cwePad = if ($cweMeta.Id.Length -le 6) { " " } else { " " }
$snapLocalAppData = $env:LOCALAPPDATA
$snapUserProfile = $env:USERPROFILE
$snapJavaHome = $env:JAVA_HOME
$snapPath = $env:PATH
$snapSystemRoot = $env:SystemRoot
$snapNoColor = $env:NO_COLOR
$snapCallerPid = $env:JVM_CALLER_PID
$snapQueryPath = $env:QUERY_PATH
$snapSkipChecksum = $env:SKIP_CHECKSUM
$snapEAP = $ErrorActionPreference
$snapLocation = (Get-Location).Path
$regEnvKeySnap = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)
$snapRegUserPath = try { if ($regEnvKeySnap) { $regEnvKeySnap.GetValue('Path', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) } else { $null } } finally { if ($regEnvKeySnap) { $regEnvKeySnap.Close() } }
$snapRegJavaHome = try { (Get-ItemProperty -Path 'HKCU:\Environment' -Name 'JAVA_HOME' -ErrorAction SilentlyContinue).JAVA_HOME } catch { $null }
$sw = [System.Diagnostics.Stopwatch]::StartNew()
try {
& { & $TestLogic } 6>$null | Out-Null
$sw.Stop()
$elapsed = $sw.ElapsedMilliseconds
$script:GlobalPassed++
$suiteEntry.Passed++
$suiteEntry.ElapsedMs += $elapsed
Write-Host " ${cGreen}[PASS]${cReset} $cweBadge$cwePad$Name ${cGray}($elapsed ms)${cReset}"
$script:TestResults.Add([PSCustomObject]@{
SuiteId = $suiteEntry.Id
SuiteTitle = $suiteEntry.Name
Suite = $Suite
CweId = $cweMeta.Id
CweIds = $allCweIds
CweShort = $cweMeta.Short
Name = $Name
Status = "PASS"
Error = $null
Duration = $elapsed
})
} catch {
$sw.Stop()
$elapsed = $sw.ElapsedMilliseconds
$script:GlobalFailed++
$suiteEntry.Failed++
$suiteEntry.ElapsedMs += $elapsed
Write-Host " ${cRed}[FAIL]${cReset} $cweBadge$cwePad$Name ${cGray}($elapsed ms)${cReset}" -ForegroundColor Red
Write-Host " Error: $($_.Exception.Message)" -ForegroundColor DarkRed
$script:TestResults.Add([PSCustomObject]@{
SuiteId = $suiteEntry.Id
SuiteTitle = $suiteEntry.Name
Suite = $Suite
CweId = $cweMeta.Id
CweIds = $allCweIds
CweShort = $cweMeta.Short
Name = $Name
Status = "FAIL"
Error = $_.Exception.Message
Duration = $elapsed
})
} finally {
$env:LOCALAPPDATA = $snapLocalAppData
$env:USERPROFILE = $snapUserProfile
$env:JAVA_HOME = $snapJavaHome
$env:PATH = $snapPath
$env:SystemRoot = $snapSystemRoot
$env:NO_COLOR = $snapNoColor
$env:JVM_CALLER_PID = $snapCallerPid
$env:QUERY_PATH = $snapQueryPath
$env:SKIP_CHECKSUM = $snapSkipChecksum
$ErrorActionPreference = $snapEAP
if ($null -ne $snapRegUserPath) {
$regEnvKeyRest = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
try {
$curRegPath = $regEnvKeyRest.GetValue('Path', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
if ($curRegPath -ne $snapRegUserPath) {
$regEnvKeyRest.SetValue('Path', $snapRegUserPath, [Microsoft.Win32.RegistryValueKind]::ExpandString)
}
} finally {
if ($regEnvKeyRest) { $regEnvKeyRest.Close() }
}
}
if ($null -ne $snapRegJavaHome) {
Set-ItemProperty -Path 'HKCU:\Environment' -Name 'JAVA_HOME' -Value $snapRegJavaHome -Type String -ErrorAction SilentlyContinue
}
foreach ($candDir in @((Get-Location).Path, $snapLocation, $RepoRoot, $ScriptDir)) {
if ($candDir) {
$literalNullFile = Join-Path $candDir '$null'
if (Test-Path -LiteralPath $literalNullFile) {
Remove-Item -LiteralPath $literalNullFile -Force -ErrorAction SilentlyContinue
}
}
}
if ($snapLocation -and (Test-Path -LiteralPath $snapLocation)) {
Set-Location -LiteralPath $snapLocation
}
}
}
}
}
function Assert-True {
param([bool]$Condition, [string]$Message)
if (-not $Condition) { throw $Message }
}
function Assert-Contains {
param([string]$Haystack, [string]$Needle, [string]$Message)
if ($Haystack.IndexOf($Needle, [System.StringComparison]::OrdinalIgnoreCase) -lt 0) {
throw "$Message `nExpected substring: '$Needle'`nActual output:`n$Haystack"
}
}
function Assert-NotContains {
param([string]$Haystack, [string]$Needle, [string]$Message)
if ($Haystack.IndexOf($Needle, [System.StringComparison]::OrdinalIgnoreCase) -ge 0) {
throw "$Message `nForbidden substring found: '$Needle'`nActual output:`n$Haystack"
}
}
function Assert-False {
param([bool]$Condition, [string]$Message)
if ($Condition) { throw $Message }
}
function Assert-Equals {
param($Actual, $Expected, [string]$Message)
if ($Actual -ne $Expected) {
throw "$Message `nExpected: '$Expected'`nActual: '$Actual'"
}
}
function Assert-PathExists {
param([string]$Path, [string]$Message)
if (-not (Test-Path -LiteralPath $Path)) {
throw "$Message `nExpected path to exist: '$Path'"
}
}
function Assert-PathNotExists {
param([string]$Path, [string]$Message)
if (Test-Path -LiteralPath $Path) {
throw "$Message `nPath unexpectedly exists: '$Path'"
}
}
# ------------------------------------------------------------------------------
# Test Environment Sandbox Isolation
# ------------------------------------------------------------------------------
$SandboxRoot = Join-Path $env:TEMP "jvm_sec_test_$([System.Guid]::NewGuid().ToString('N'))"
New-Item -ItemType Directory -Path $SandboxRoot -Force | Out-Null
$FakeLocalAppData = Join-Path $SandboxRoot "LocalAppData"
$FakeUserProfile = Join-Path $SandboxRoot "UserProfile"
New-Item -ItemType Directory -Path $FakeLocalAppData -Force | Out-Null
New-Item -ItemType Directory -Path $FakeUserProfile -Force | Out-Null
New-Item -ItemType Directory -Path (Join-Path $FakeLocalAppData "DiamTek\JVM") -Force | Out-Null
# Create simulated fake JDK
$FakeJdkDir = Join-Path $SandboxRoot "TargetJDK_21"
New-Item -ItemType Directory -Path (Join-Path $FakeJdkDir "bin") -Force | Out-Null
Set-Content -Path (Join-Path $FakeJdkDir "bin\java.exe") -Value "MZ_FAKE_JAVA_BINARY"
Set-Content -Path (Join-Path $FakeJdkDir "release") -Value "JAVA_VERSION=21.0.2`r`nIMPLEMENTOR=`"Eclipse Adoptium`""
Set-Content -Path (Join-Path $FakeJdkDir "canary.txt") -Value "CRITICAL_SENTINEL_DO_NOT_DELETE"
Write-Host ""
Write-Host "$cCyan$cBold====================================================================================$cReset"
Write-Host "$cCyan$cBold DiamTek JVM Automated Security & Adversarial Test Suite $cReset"
Write-Host "$cCyan$cBold====================================================================================$cReset"
Write-Host " Repository: $RepoRoot"
Write-Host " Sandbox : $SandboxRoot"
try {
# ==========================================================================
# SUITE 1: Adversarial Inputs & Fuzzing Defense
# ==========================================================================
Run-TestCase "Adversarial" "Path Traversal in 'jvm link' with '..'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" ../evil_link" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on '..'"
Assert-Contains $out "Link name cannot contain" "Output must reject '..'"
}
Run-TestCase "Adversarial" "Path Traversal in 'jvm link' with forward slash '/'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" evil/link" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on '/'"
Assert-Contains $out "Link name cannot contain path separators" "Output must reject '/'"
}
Run-TestCase "Adversarial" "Path Traversal in 'jvm link' with backslash '\'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" evil\link" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on '\'"
Assert-Contains $out "Link name cannot contain path separators" "Output must reject '\'"
}
Run-TestCase "Adversarial" "Path Traversal in 'jvm link' with single dot '.'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" ." 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on '.'"
Assert-Contains $out "'.' is forbidden" "Output must forbid '.'"
}
Run-TestCase "Adversarial" "Reserved keyword rejection in 'jvm link' with 'current'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" current" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on 'current'"
Assert-Contains $out "'current' is a reserved keyword" "Output must guard 'current'"
}
Run-TestCase "Adversarial" "Path Traversal in 'jvm unlink' with '..'" {
$out = & cmd.exe /c "call `"$JvmBat`" unlink .." 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on '..'"
Assert-Contains $out "Link name cannot contain" "Unlink must reject '..'"
}
Run-TestCase "Adversarial" "Reserved keyword rejection in 'jvm unlink' with 'current'" {
$out = & cmd.exe /c "call `"$JvmBat`" unlink current" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on 'current'"
Assert-Contains $out "'current' is a reserved keyword" "Unlink must guard 'current'"
}
Run-TestCase "Adversarial" "Ecosystem candidate switch path traversal rejection" {
$out = & cmd.exe /c "call `"$JvmBat`" maven ../../evil" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on candidate version traversal"
Assert-Contains $out "Version identifier cannot contain" "SwitchCandidate must reject '..'"
}
Run-TestCase "Adversarial" "Ecosystem candidate switch 'current' keyword rejection" {
$out = & cmd.exe /c "call `"$JvmBat`" gradle current" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on candidate version 'current'"
Assert-Contains $out "'current' is a reserved keyword" "SwitchCandidate must guard 'current'"
}
Run-TestCase "Adversarial" "Candidate installation path traversal rejection" {
$out = & cmd.exe /c "call `"$JvmBat`" install maven 3.9/../../evil" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on install version traversal"
Assert-Contains $out "Version identifier cannot contain" "InstallCandidate must reject separators"
}
Run-TestCase "Adversarial" "Candidate uninstallation traversal rejection" {
$out = & cmd.exe /c "call `"$JvmBat`" uninstall maven .." 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on uninstall traversal"
Assert-Contains $out "Version identifier cannot contain" "UninstallCandidate must reject traversal"
}
Run-TestCase "Adversarial" "Metacharacter command injection defense in .java-version" {
$testDir = Join-Path $SandboxRoot "InjectionTest_JavaVersion"
New-Item -ItemType Directory -Path $testDir -Force | Out-Null
$pwnFile = Join-Path $testDir "PWNED.txt"
# Craft malicious .java-version with command chaining
Set-Content -Path (Join-Path $testDir ".java-version") -Value "21 & echo INJECTED > `"$pwnFile`""
Push-Location $testDir
try {
$out = & cmd.exe /c "call `"$JvmBat`" current" 2>&1 | Out-String
Assert-True (-not (Test-Path $pwnFile)) "Command injection payload MUST NOT execute"
} finally {
Pop-Location
}
}
Run-TestCase "Adversarial" "Pipe command injection defense in .java-version" {
$testDir = Join-Path $SandboxRoot "InjectionTest_Pipe"
New-Item -ItemType Directory -Path $testDir -Force | Out-Null
$pwnFile = Join-Path $testDir "PWNED_PIPE.txt"
Set-Content -Path (Join-Path $testDir ".java-version") -Value "21 | echo INJECTED > `"$pwnFile`""
Push-Location $testDir
try {
$out = & cmd.exe /c "call `"$JvmBat`" current" 2>&1 | Out-String
Assert-True (-not (Test-Path $pwnFile)) "Pipe injection payload MUST NOT execute"
} finally {
Pop-Location
}
}
Run-TestCase "Adversarial" "Metacharacter command injection defense in .sdkmanrc" {
$testDir = Join-Path $SandboxRoot "InjectionTest_Sdkmanrc"
New-Item -ItemType Directory -Path $testDir -Force | Out-Null
$pwnFile = Join-Path $testDir "PWNED_SDK.txt"
Set-Content -Path (Join-Path $testDir ".sdkmanrc") -Value "java=21.0.2-tem & echo INJECTED > `"$pwnFile`""
Push-Location $testDir
try {
$out = & cmd.exe /c "call `"$JvmBat`" current" 2>&1 | Out-String
Assert-True (-not (Test-Path $pwnFile)) ".sdkmanrc command injection payload MUST NOT execute"
} finally {
Pop-Location
}
}
Run-TestCase "Adversarial" "install.ps1 branch traversal parameter rejection" {
$installPs1 = Join-Path $RepoRoot "install.ps1"
$out = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $installPs1 -Branch "../malicious/tag" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "install.ps1 must fail on branch traversal"
Assert-Contains $out "Invalid branch or tag name" "install.ps1 must reject '..' in -Branch"
}
Run-TestCase "Adversarial" "PowerShell profile hook injection filter in Set-JvmVar" {
# Test the regex filter used in profile hook Set-JvmVar: if ($NewValue -match '[\0;&|<>`"\r\n\$]') { return }
$filterRegex = '[\0;&|<>`"\r\n\$]'
$maliciousValues = @(
'C:\Java\jdk-21 & calc.exe',
'C:\Java\jdk-21; calc.exe',
'C:\Java\jdk-21 | calc.exe',
"C:\Java\jdk-21`$(calc.exe)",
"C:\Java\jdk-21`ncalc.exe",
"C:\Java\jdk-21`0calc.exe",
'C:\Java\jdk-21" & calc.exe'
)
foreach ($val in $maliciousValues) {
Assert-True ($val -match $filterRegex) "Profile hook filter must catch payload: $val"
}
}
Run-TestCase "Adversarial" "Trailing dot Win32 bypass in 'jvm link' with 'current.'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" current." 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on 'current.'"
Assert-Contains $out "reserved keyword" "Output must guard 'current' with trailing dot"
}
Run-TestCase "Adversarial" "Trailing space Win32 bypass in 'jvm link' with 'current '" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" `"current `"" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on 'current '"
Assert-Contains $out "reserved keyword" "Output must guard 'current' with trailing space"
}
Run-TestCase "Adversarial" "DOS reserved device rejection in 'jvm link' (CON, PRN, AUX, NUL)" {
foreach ($dev in @('CON', 'PRN', 'AUX', 'NUL', 'COM1', 'LPT1')) {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" $dev" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on DOS device $dev"
Assert-Contains $out "Invalid link name" "Output must reject DOS device $dev"
}
}
Run-TestCase "Adversarial" "Poison characters in 'jvm link' (&, |, <, >, ^, %, !)" {
$poisons = @('foo&bar', 'foo|bar', 'foo<bar', 'foo>bar', 'foo^bar', 'foo^%bar', 'foo!bar')
$runnerBat = Join-Path $SandboxRoot "test_poison_link.bat"
foreach ($p in $poisons) {
[System.IO.File]::WriteAllText($runnerBat, "@chcp 65001 >nul`r`n@`"$JvmBat`" link `"$FakeJdkDir`" `"$p`"`r`n", [System.Text.UTF8Encoding]::new($false))
$out = & cmd.exe /c $runnerBat 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on poison character: $p"
}
Remove-Item $runnerBat -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath (Join-Path $RepoRoot "bar") -Force -ErrorAction SilentlyContinue
}
Run-TestCase "Adversarial" "Alternative Data Stream (ADS) rejection in 'jvm link'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" test:stream" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on NTFS ADS syntax"
Assert-Contains $out "Invalid link name" "Output must reject ':' stream separator"
}
Run-TestCase "Adversarial" "jvm which command traversal rejection" {
$out = & cmd.exe /c "call `"$JvmBat`" which ../../evil" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on 'jvm which ../../evil'"
Assert-Contains $out "Invalid candidate name" "Output must reject traversal in which"
}
Run-TestCase "Adversarial" "jvm which poison character rejection" {
$runnerBat = Join-Path $SandboxRoot "test_poison_which.bat"
[System.IO.File]::WriteAllText($runnerBat, "@chcp 65001 >nul`r`n@call `"$JvmBat`" which `"foo&bar`"`r`n@exit /b %errorlevel%`r`n", [System.Text.UTF8Encoding]::new($false))
$out = & cmd.exe /c $runnerBat 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on 'jvm which foo&bar'"
Assert-Contains $out "Invalid candidate name" "Output must reject poison character in which"
Remove-Item $runnerBat -Force -ErrorAction SilentlyContinue
}
Run-TestCase "Adversarial" ".sdkmanrc candidate traversal rejection in session mode" {
$testDir = Join-Path $SandboxRoot "InjectionTest_SdkTraversal"
New-Item -ItemType Directory -Path $testDir -Force | Out-Null
Set-Content -Path (Join-Path $testDir ".sdkmanrc") -Value "maven=../../Windows`ngradle=../test"
Push-Location $testDir
try {
$sessTarget = Join-Path $env:TEMP ".jvm_session_target"
if (Test-Path $sessTarget) { Remove-Item $sessTarget -Force -ErrorAction SilentlyContinue }
$out = & cmd.exe /c "call `"$JvmBat`" status" 2>&1 | Out-String
if (Test-Path $sessTarget) {
$content = Get-Content $sessTarget -Raw
Assert-NotContains $content "MAVEN_HOME=.*Windows" "Traversed path must not be recorded in session target"
Remove-Item $sessTarget -Force -ErrorAction SilentlyContinue
}
} finally {
Pop-Location
}
}
Run-TestCase "Adversarial" "Leading hyphen flag injection defense in 'jvm link'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" --evil-flag" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on '--evil-flag'"
Assert-Contains $out "Invalid link name" "Output must reject leading hyphen"
}
Run-TestCase "Adversarial" "Multiple trailing dots Win32 bypass defense in 'jvm link'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" current...." 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on 'current....'"
Assert-True (($out -match "reserved keyword") -or ($out -match "cannot contain '\.\.'")) "Must reject multi-dot bypass"
}
Run-TestCase "Adversarial" "Multiple trailing spaces Win32 bypass defense in 'jvm link'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" `"current `"" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on 'current '"
Assert-Contains $out "reserved keyword" "Output must guard 'current' with multiple trailing spaces"
}
Run-TestCase "Adversarial" "Semicolon command chaining rejection in candidate version" {
$out = & cmd.exe /c "call `"$JvmBat`" maven `"3.9;calc`"" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on candidate version with semicolon"
Assert-Contains $out "Invalid version identifier" "Output must reject semicolon"
}
Run-TestCase "Adversarial" "Asterisk wildcard rejection in 'jvm link'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" `"foo*bar`"" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on wildcard asterisk"
Assert-Contains $out "Invalid link name" "Output must reject asterisk wildcard"
}
Run-TestCase "Adversarial" "Question mark wildcard rejection in 'jvm link'" {
$out = & cmd.exe /c "call `"$JvmBat`" link `"$FakeJdkDir`" `"foo?bar`"" 2>&1 | Out-String
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on wildcard question mark"
Assert-Contains $out "Invalid link name" "Output must reject question mark wildcard"
}
Run-TestCase "Adversarial" "Pinned System Binaries CWD Planting Defense" {
$content = Get-Content $JvmBat -Raw
$bins = @('CMD_BIN', 'PS_BIN', 'FINDSTR_BIN', 'REG_BIN', 'FSUTIL_BIN', 'WHERE_BIN', 'TIMEOUT_BIN', 'CHOICE_BIN', 'CHCP_BIN')
foreach ($b in $bins) {
Assert-Contains $content "set `"$b=%SYS32%\" "jvm.bat must pin $b to %SYS32% to prevent binary planting"
}
}
Run-TestCase "Adversarial" "Metacharacter command injection defense in 'jvm pin'" {
$testDir = Join-Path $SandboxRoot "PinInjectionTest"
New-Item -ItemType Directory -Path $testDir -Force | Out-Null
Push-Location $testDir
try {
$prevEAP = $ErrorActionPreference; $ErrorActionPreference = 'Continue'
$out = & cmd.exe /c "call `"$JvmBat`" pin `"21;calc`"" 2>&1 | Out-String
$ErrorActionPreference = $prevEAP
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on injection in 'jvm pin'"
Assert-Contains $out "Invalid version identifier for pin" "Output must reject metacharacters in 'jvm pin'"
} finally {
Pop-Location
}
}
Run-TestCase "Adversarial" "Path Traversal in 'jvm exec' command" {
$prevEAP = $ErrorActionPreference; $ErrorActionPreference = 'Continue'
$out = & cmd.exe /c "call `"$JvmBat`" exec ../../evil -- java -version" 2>&1 | Out-String
$ErrorActionPreference = $prevEAP
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on traversal in 'jvm exec'"
Assert-Contains $out "Invalid target version for exec" "Output must reject traversal in 'jvm exec'"
}
Run-TestCase "Adversarial" "PowerShell command injection defense in 'jvm install' candidate version" {
$testDir = Join-Path $SandboxRoot "InstallInjectTest"
New-Item -ItemType Directory -Path $testDir -Force | Out-Null
$pwnFile = Join-Path $testDir "INSTALL_PWNED.txt"
$prevEAP = $ErrorActionPreference; $ErrorActionPreference = 'Continue'
$out = & cmd.exe /c "call `"$JvmBat`" install maven `"3.9;calc`"" 2>&1 | Out-String
$ErrorActionPreference = $prevEAP
Assert-True ($LASTEXITCODE -ne 0) "Expected failure on injection in candidate version"
Assert-True (-not (Test-Path $pwnFile)) "Injected payload in candidate version MUST NOT execute"
Assert-Contains $out "Invalid version identifier" "Output must reject injection in candidate version"
}
Run-TestCase "Adversarial" "Pre-delayed-expansion ':RejectExclamationArg' across positions %~1..%~5" {
$argVectors = @(
'!PATH!',
'use "jdk!21"',
'install maven "!lead"',
'exec 21 -- "trail!"',
'exec 21 -- java "mid!dle"'
)
foreach ($vec in $argVectors) {
$prevEAP = $ErrorActionPreference; $ErrorActionPreference = 'Continue'
$out = & cmd.exe /c "call `"$JvmBat`" $vec" 2>&1 | Out-String
$ErrorActionPreference = $prevEAP
Assert-True ($LASTEXITCODE -ne 0) "Expected ':RejectExclamationArg' failure for vector: $vec"
Assert-Contains $out "poison character '!' is forbidden" "Output must reject '!' in vector: $vec"
}
}
Run-TestCase "Adversarial" "Embedded double-quote smuggling rejection in ':VSI_CharLoop'" {
$testDir = Join-Path $SandboxRoot "QuoteSmuggleTest"
New-Item -ItemType Directory -Path $testDir -Force | Out-Null
Push-Location $testDir
try {
$prevEAP = $ErrorActionPreference; $ErrorActionPreference = 'Continue'
# 1. End-to-end CLI check: smuggled quote must abort with non-zero exit code and never write .java-version
$outPin = & cmd.exe /c "call `"$JvmBat`" pin 21^`"pwn" 2>&1 | Out-String
$pinExit = $LASTEXITCODE
$ErrorActionPreference = $prevEAP
Assert-True ($pinExit -ne 0) "jvm pin must fail closed on smuggled double quote"
Assert-PathNotExists (Join-Path $testDir ".java-version") ".java-version must not be written on quote smuggling"
# 2. Direct unit verification of :ValidateStrictIdentifier / :VSI_CharLoop on embedded '"'
$batRaw = Get-Content $JvmBat -Raw
$vsiMatch = [regex]::Match($batRaw, '(?s)(:VSI_CharLoop\r?\n.*?)(?=\r?\n:GetCandidateEnvVar)')
Assert-True $vsiMatch.Success "Must locate :VSI_CharLoop in jvm.bat"
$vsiHarness = Join-Path $testDir "vsi_quote_harness.bat"
$vsiCode = @"
@echo off
setlocal disabledelayedexpansion
setlocal enabledelayedexpansion
set _VSI_DQ="
set _VSI_VAL=21"pwn
set "_VSI_REM=!_VSI_VAL!"
goto :VSI_CharLoop
$($vsiMatch.Groups[1].Value)
"@
[System.IO.File]::WriteAllText($vsiHarness, ($vsiCode -replace "\r?\n", "`r`n"), [System.Text.UTF8Encoding]::new($false))
$null = & cmd.exe /c "call `"$vsiHarness`"" 2>&1
Assert-Equals $LASTEXITCODE 1 ":VSI_CharLoop must return exit code 1 when _VSI_VAL contains an embedded double-quote"
} finally {
Pop-Location
}
}
Run-TestCase "Adversarial" "'--vendor' flag poisoning and unsupported vendor dispatch rejection" {
$prevEAP = $ErrorActionPreference; $ErrorActionPreference = 'Continue'
$outSwitch = & cmd.exe /c "call `"$JvmBat`" 21 --vendor `"../../evil_vendor`"" 2>&1 | Out-String
$switchExit = $LASTEXITCODE
$outUpdate = & cmd.exe /c "call `"$JvmBat`" update 21 --vendor `"oracle;calc`"" 2>&1 | Out-String
$updateExit = $LASTEXITCODE
$ErrorActionPreference = $prevEAP
Assert-True ($switchExit -ne 0) "Switching with poisoned --vendor must fail closed"
Assert-Contains $outSwitch "Invalid vendor identifier" "Poisoned --vendor must be blocked by ValidateStrictIdentifier"
Assert-True ($updateExit -ne 0) "Updating with poisoned --vendor must fail closed"
Assert-Contains $outUpdate "Invalid vendor identifier" "Poisoned --vendor in update must be blocked by ValidateStrictIdentifier"
$batContent = Get-Content $JvmBat -Raw
Assert-NotContains $batContent "goto :Resolve_!CLI_VENDOR!" "jvm.bat must not use unvalidated dynamic goto on CLI_VENDOR"
Assert-Contains $batContent "Unknown or unsupported vendor: !CLI_VENDOR!" "jvm.bat must explicitly reject unknown vendors"
}
Run-TestCase "Adversarial" "'jvm channel' invalid value rejection and 'jvm open' target allowlisting" {
$origLocalAppData = $env:LOCALAPPDATA
try {
$env:LOCALAPPDATA = $FakeLocalAppData
$channelFile = Join-Path $FakeLocalAppData "DiamTek\JVM\channel.txt"
if (Test-Path -LiteralPath $channelFile) { Remove-Item -LiteralPath $channelFile -Force }
$prevEAP = $ErrorActionPreference; $ErrorActionPreference = 'Continue'
$outChan = & cmd.exe /c "call `"$JvmBat`" channel `"../../evil_branch`"" 2>&1 | Out-String
$outOpen = & cmd.exe /c "call `"$JvmBat`" open candidates" 2>&1 | Out-String
$openExit = $LASTEXITCODE
$ErrorActionPreference = $prevEAP
Assert-Contains $outChan "Unknown channel" "jvm channel must reject invalid channel names"
Assert-Contains $outChan "Valid options are 'stable' or 'nightly'" "jvm channel must state valid options"
Assert-PathNotExists $channelFile "Invalid channel argument must NOT create or modify channel.txt"
Assert-True ($openExit -ne 0) "jvm open must fail closed when allowlisted target directory does not exist"
Assert-Contains $outOpen "Target path does not exist" "jvm open must report missing target path without launching explorer.exe"
$batContent = Get-Content $JvmBat -Raw
Assert-NotContains $batContent 'set "OPEN_PATH=!CLI_TARGET!"' "jvm open must never assign raw CLI_TARGET directly to OPEN_PATH"
} finally {
$env:LOCALAPPDATA = $origLocalAppData
}
}
Run-TestCase "Adversarial" "Static code audit: 'for /f' subshells must never quote '%..._BIN%' binaries" {
$lines = Get-Content $JvmBat
$violations = @()
for ($i = 0; $i -lt $lines.Count; $i++) {
$line = $lines[$i]
# 1. No pinned system binary (%..._BIN%) may be wrapped in quotes inside for /f ('...')
if ($line -match '(?i)^\s*for\s+/f\b.*\bin\s*\(\s*''[^'']*\"%[A-Z0-9_]+_BIN%\"') {
$violations += "Line $($i + 1) (quoted %..._BIN%): $($line.Trim())"
}
# 2. No for /f ('"..."..."..."') command may start AND end with a SINGLE quote (not ""..."" wrapper) when containing multiple quoted segments
if ($line -match '(?i)^\s*for\s+/f\b.*\bin\s*\(\s*''(\"(?!\")[^'']+\"[^'']*\"[^'']+?(?<!\")\")''\s*\)') {
$violations += "Line $($i + 1) (unwrapped multi-quote cmd.exe /c stripping hazard): $($line.Trim())"
}
}
Assert-True ($violations.Count -eq 0) ("Found 'for /f' quote-stripping hazard in jvm.bat:`n" + ($violations -join "`n"))
}
Run-TestCase "Adversarial" "':ValidateStrictIdentifier' clean execution on 'jvm which java' and leading-hyphen flag injection rejection" {
$prevEAP = $ErrorActionPreference; $ErrorActionPreference = 'Continue'
$outWhichClean = & cmd.exe /c "call `"$JvmBat`" which java" 2>&1 | Out-String
$outHyphen = & cmd.exe /c "call `"$JvmBat`" pin `"-ExecutionPolicy`"" 2>&1 | Out-String
$hyphenExit = $LASTEXITCODE
$ErrorActionPreference = $prevEAP
Assert-NotContains $outWhichClean "is not recognized as an internal or external command" "jvm which java must not emit CMD quote-parser errors"
Assert-True ($hyphenExit -ne 0) "Leading hyphen flag injection must be rejected by :ValidateStrictIdentifier"
Assert-Contains $outHyphen "Invalid version identifier" "Leading hyphen must be rejected with clear diagnostic"
}
# ==========================================================================
# SUITE 2: Registry & Environment Variable Boundary & Elevation Tests
# ==========================================================================
Run-TestCase "Registry" "User PATH REG_EXPAND_SZ preservation during installation" {
# Verify that setting User PATH via registry preserves ExpandString kind
$testHive = "HKCU:\Environment"
$originalKind = (Get-Item -Path $testHive).GetValueKind("Path")
Assert-True ($originalKind -in @([Microsoft.Win32.RegistryValueKind]::ExpandString, [Microsoft.Win32.RegistryValueKind]::String)) "Valid initial kind"
$testValName = "TestJvmPath"
try {
# Simulate JVM registry update logic
[Microsoft.Win32.Registry]::SetValue("HKEY_CURRENT_USER\Environment", $testValName, "%USERPROFILE%\dummy;%SystemRoot%\System32", [Microsoft.Win32.RegistryValueKind]::ExpandString)
$kind = (Get-Item -Path $testHive).GetValueKind($testValName)
Assert-True ($kind -eq [Microsoft.Win32.RegistryValueKind]::ExpandString) "Registry ValueKind must be ExpandString"
# Verify unexpanded content is preserved
$envKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey("Environment")
try {
$raw = $envKey.GetValue($testValName, "", [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
} finally {
if ($null -ne $envKey) { $envKey.Close() }
}
Assert-Contains $raw "%USERPROFILE%" "Unexpanded environment variable tokens must NOT be converted to static strings"
} finally {
# Clean test key unconditionally even if an assertion throws
Remove-ItemProperty -Path $testHive -Name $testValName -Force -ErrorAction SilentlyContinue
}
}
Run-TestCase "Registry" "Elevation payload generation uses Base64 UTF-16LE without temp files" {