Repository navigation
Expand file tree
/
Copy pathjava4shell_host_check.py
More file actions
359 lines (298 loc) · 12 KB
/
Copy pathjava4shell_host_check.py
File metadata and controls
359 lines (298 loc) · 12 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
#!/usr/bin/env python3
"""Local host check for CVE-2026-114938 (Java4Shell).
Finds every java binary it can reach on this host, checks its version,
effective JVM flags, and the x86-64 CPU flags required by the vulnerable
AVX-512 VBMI Base64 intrinsic. It does not inspect running JVMs or
containers.
"""
from __future__ import annotations
import argparse
import json
import os
import platform
import re
import shutil
import subprocess
import sys
from typing import Dict, List, Optional, Sequence, Set, Tuple
try:
from .java4shell_scan import FIXED_BUILDS, classify_version, parse_version
except ImportError:
from java4shell_scan import FIXED_BUILDS, classify_version, parse_version
REQUIRED_CPU_FLAGS = ("avx512f", "avx512bw", "avx512vbmi", "bmi2")
GLOBAL_NOTES = (
"This checks java binaries on this host, not running JVMs or containers.",
"Vendor backports can report an older version while already being patched.",
)
_PROBED_NAMES = ("java", "java.exe")
_PROPERTY_RE = re.compile(r"^\s*([A-Za-z0-9_.]+)\s*=\s*(.*?)\s*$", re.M)
_FLAG_RE = re.compile(r"^\s*(\w+)\s*=\s*(\S+)", re.M)
_VERSION_RE = re.compile(r'version\s+"([^"]+)"')
_COMMON_JAVA_DIRS = (
"/usr/lib/jvm",
"/usr/java",
"/usr/local/java",
"/usr/local/jdk",
"/opt/java",
"/opt/jdk",
"/opt/java/openjdk",
"~/.sdkman/candidates/java",
"~/.jdks",
"~/.gradle/jdks",
)
def run_command(command: Sequence[str], timeout: float = 15.0) -> Tuple[int, str, str]:
try:
completed = subprocess.run(
command,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
return completed.returncode, completed.stdout, completed.stderr
except (OSError, subprocess.TimeoutExpired) as exc:
return 127, "", str(exc)
def find_java(explicit: Optional[str]) -> Optional[str]:
if explicit:
if os.path.isfile(explicit) and os.access(explicit, os.X_OK):
return explicit
return shutil.which(explicit)
return shutil.which("java")
def _is_executable(path: str) -> bool:
return os.path.isfile(path) and os.access(path, os.X_OK)
def _walk_java_binaries(base: str, max_depth: int) -> List[str]:
found: List[str] = []
base_depth = base.rstrip(os.sep).count(os.sep)
for root, dirs, files in os.walk(base):
depth = root.count(os.sep) - base_depth
if depth >= max_depth:
dirs.clear()
for name in _PROBED_NAMES:
if name in files:
candidate = os.path.join(root, name)
if _is_executable(candidate):
found.append(candidate)
return found
def discover_java_binaries(
explicit: Optional[Sequence[str]] = None,
max_depth: int = 4,
) -> List[str]:
"""Return unique, resolved java binaries worth probing.
Explicit paths win. Without them, this scans JAVA_HOME, PATH, and the
usual install directories for additional JDKs.
"""
candidates: List[str] = []
if explicit:
for entry in explicit:
resolved = find_java(entry)
if resolved:
candidates.append(resolved)
else:
java_home = os.environ.get("JAVA_HOME")
if java_home:
for name in _PROBED_NAMES:
candidate = os.path.join(java_home, "bin", name)
if _is_executable(candidate):
candidates.append(candidate)
on_path = shutil.which("java")
if on_path:
candidates.append(on_path)
search_roots: List[str] = [os.path.expanduser(path) for path in _COMMON_JAVA_DIRS]
if platform.system() == "Windows":
search_roots.extend(
[
r"C:\Program Files\Java",
r"C:\Program Files\Eclipse Adoptium",
r"C:\Program Files\Microsoft",
r"C:\Program Files\Amazon Corretto",
r"C:\Program Files\Zulu",
]
)
for base in search_roots:
if os.path.isdir(base):
candidates.extend(_walk_java_binaries(base, max_depth))
unique: List[str] = []
seen = set()
for candidate in candidates:
try:
real = os.path.realpath(candidate)
except OSError:
continue
if not _is_executable(real) or real in seen:
continue
seen.add(real)
unique.append(real)
return unique
def read_properties(java: str) -> Dict[str, str]:
_, stdout, stderr = run_command([java, "-XshowSettings:properties", "-version"])
properties: Dict[str, str] = {}
for match in _PROPERTY_RE.finditer(stdout + "\n" + stderr):
properties[match.group(1)] = match.group(2)
return properties
def read_flags(java: str) -> Dict[str, str]:
_, stdout, stderr = run_command([java, "-XX:+PrintFlagsFinal", "-version"])
flags: Dict[str, str] = {}
for match in _FLAG_RE.finditer(stdout + "\n" + stderr):
flags[match.group(1)] = match.group(2)
return flags
def read_version_text(java: str) -> str:
_, stdout, stderr = run_command([java, "-version"])
match = _VERSION_RE.search(stdout + "\n" + stderr)
return match.group(1) if match else ""
def read_cpu_flags() -> Tuple[Set[str], str]:
system = platform.system().lower()
if system == "linux":
try:
with open("/proc/cpuinfo", "r", encoding="utf-8", errors="replace") as handle:
for line in handle:
if line.lower().startswith("flags"):
return set(line.split(":", 1)[1].split()), "/proc/cpuinfo"
except OSError:
return set(), "unavailable"
return set(), "unavailable"
if system == "darwin":
flags: Set[str] = set()
for key in ("machdep.cpu.features", "machdep.cpu.leaf7_features"):
_, stdout, _ = run_command(["sysctl", "-n", key])
flags.update(stdout.lower().split())
return flags, "sysctl"
return set(), "unavailable"
def parse_use_avx(value: Optional[str]) -> Optional[int]:
if value is None:
return None
try:
return int(value)
except ValueError:
return None
def check_host(java_path: Optional[str]) -> Dict[str, object]:
java = find_java(java_path)
if not java:
return {
"java": None,
"verdict": "UNKNOWN",
"notes": ["No java binary found. Pass --java /path/to/java."],
}
version_text = read_version_text(java)
properties = read_properties(java)
flags = read_flags(java)
cpu_flags, cpu_source = read_cpu_flags()
reported_version = properties.get("java.version") or version_text
version_status, version_detail = classify_version(reported_version)
parsed = parse_version(reported_version)
use_base64 = flags.get("UseBASE64Intrinsics")
use_avx = parse_use_avx(flags.get("UseAVX"))
mitigated = use_base64 == "false" or (use_avx is not None and use_avx <= 2)
machine = platform.machine().lower()
x86 = machine in ("x86_64", "amd64")
hardware_eligible = x86 and all(flag in cpu_flags for flag in REQUIRED_CPU_FLAGS)
notes: List[str] = []
if version_status == "not_affected":
verdict = "PATCHED_OR_OUTSIDE_RANGE"
elif mitigated:
verdict = "MITIGATED"
notes.append("The vulnerable intrinsic is disabled by the current JVM flags, but upgrading is still recommended.")
elif version_status == "affected" and hardware_eligible:
verdict = "POTENTIALLY_AFFECTED"
notes.append(f"Upgrade to {FIXED_BUILDS.get(parsed.major) or 'a fixed vendor build'} or later and restart the JVM.")
elif version_status == "affected":
verdict = "NOT_EXPLOITABLE_ON_THIS_CPU"
notes.append("This CPU does not expose all four required flags. Other hosts or containers may differ.")
else:
verdict = "UNKNOWN"
notes.append("The JVM version or hardware state could not be determined.")
notes.extend(GLOBAL_NOTES)
return {
"java": java,
"java_version": reported_version,
"vendor": properties.get("java.vendor"),
"java_home": properties.get("java.home"),
"os_arch": properties.get("os.arch") or machine,
"version_assessment": version_status,
"version_detail": version_detail,
"use_base64_intrinsics": use_base64,
"use_avx": use_avx,
"mitigated": mitigated,
"cpu_source": cpu_source,
"cpu_flags": sorted(cpu_flags),
"required_cpu_flags": {
flag: flag in cpu_flags for flag in REQUIRED_CPU_FLAGS
},
"hardware_eligible": hardware_eligible,
"verdict": verdict,
"notes": notes,
}
def check_hosts(binaries: Sequence[str]) -> List[Dict[str, object]]:
return [check_host(binary) for binary in binaries]
def needs_upgrade(result: Dict[str, object]) -> bool:
return result.get("version_assessment") == "affected"
def print_human(result: Dict[str, object]) -> None:
print(f"Java: {result.get('java') or 'not found'}")
if result.get("java_version"):
print(f"Version: {result['java_version']} ({result.get('vendor') or 'unknown vendor'})")
print(f"Java home: {result.get('java_home') or 'unknown'}")
print(f"Architecture: {result.get('os_arch') or 'unknown'}")
print(f"Version assessment: {result.get('version_assessment')} ({result.get('version_detail')})")
print(f"UseBASE64Intrinsics: {result.get('use_base64_intrinsics')}")
print(f"UseAVX: {result.get('use_avx')}")
required = result.get("required_cpu_flags") or {}
print("CPU flags: " + ", ".join(f"{key}={value}" for key, value in required.items()))
print(f"Hardware eligible: {result.get('hardware_eligible')}")
print(f"Verdict: {result.get('verdict')}")
for note in result.get("notes") or []:
if note not in GLOBAL_NOTES:
print(f" {note}")
def print_report(results: Sequence[Dict[str, object]]) -> None:
print("Java4Shell (CVE-2026-114938) local check")
print(f"Runtimes found: {len(results)}")
print("")
if not results:
print("No java binary found. Pass --java /path/to/java.")
for index, result in enumerate(results, start=1):
if index > 1:
print("")
print(f"[{result.get('verdict')}] {result.get('java') or 'not found'}")
if result.get("java_version"):
print(f" Version: {result['java_version']} ({result.get('vendor') or 'unknown vendor'})")
print(f" Assessment: {result.get('version_assessment')}")
for note in result.get("notes") or []:
if note not in GLOBAL_NOTES:
print(f" {note}")
print("")
for note in GLOBAL_NOTES:
print(note)
def summarize(results: Sequence[Dict[str, object]]) -> int:
affected = [result for result in results if needs_upgrade(result)]
if not affected:
return 0
print("", file=sys.stderr)
print(
f"{len(affected)} runtime(s) need an upgrade: "
+ ", ".join(str(result.get("java")) for result in affected),
file=sys.stderr,
)
return 1
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser(
description="Check local Java runtimes for Java4Shell (CVE-2026-114938).",
epilog="Exit codes: 0 no affected runtime, 1 affected runtime found, 2 execution error.",
)
parser.add_argument(
"--java",
action="append",
help="Path to a java binary to check. Repeatable. Skips automatic discovery.",
)
parser.add_argument("--json", action="store_true", help="JSON output (always an array)")
args = parser.parse_args(argv)
try:
binaries = discover_java_binaries(args.java)
except OSError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
results = check_hosts(binaries)
if args.json:
print(json.dumps(results, indent=2))
else:
print_report(results)
return summarize(results)
if __name__ == "__main__":
sys.exit(main())