eBPF-based security platform
upatches: add the java-base64 Base64 guard agent
John Fastabend82c8af7dee35
diff --git a/tools/put-shields b/tools/put-shieldsindex faddcf76..28f4b0dc 100755--- a/tools/put-shields+++ b/tools/put-shields@@ -134,7 +134,14 @@ keys=$(realpath "$keys")mkdir "$work/out"while read -r beefile; do- built=$(cd "$work/out" && "$shirudo" bpm build "$(dirname "$beefile")" \+ # A Java shield's source is a prebuilt .jar; its build.sh --jar-only+ # makes it, where a BPF shield's source compiles in bpm build.+ dir=$(dirname "$beefile")+ if grep -q '^type = "java"' "$beefile" && [ -x "$dir/build.sh" ]; then+ ( cd "$dir" && ./build.sh --jar-only ) </dev/null ||+ die "cannot build the jar of $beefile"+ fi+ built=$(cd "$work/out" && "$shirudo" bpm build "$dir" \--file "$beefile" --version "$version" --keys-dir "$keys" </dev/null) ||die "cannot build $beefile"bee=$(basename "$(printf '%s\n' "$built" | tail -n 1)")diff --git a/upatches/java-base64/.gitignore b/upatches/java-base64/.gitignorenew file mode 100644index 00000000..3fcbfdc9--- /dev/null+++ b/upatches/java-base64/.gitignore@@ -0,0 +1,3 @@+/java-base64.jar+/*.bee+target/diff --git a/upatches/java-base64/Beefile b/upatches/java-base64/Beefilenew file mode 100644index 00000000..d21d97dc--- /dev/null+++ b/upatches/java-base64/Beefile@@ -0,0 +1,19 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo++[package]+name = "java-base64"+description = "A Java agent that blocks the OpenJDK x64 Base64 decoder tail-underflow (CVE-2026-114938)"+license = "BSD-2-Clause"+authors = ["Authors of shirudo"]++[[upatches]]+type = "java"+source = "java-base64.jar"++[upatches.tree]+id = "java-base64"+fixes = ["CVE-2026-114938"]++[upatches.tree.selector]+architecture = ["x86_64"]diff --git a/upatches/java-base64/README.md b/upatches/java-base64/README.mdnew file mode 100644index 00000000..6da80ad6--- /dev/null+++ b/upatches/java-base64/README.md@@ -0,0 +1,61 @@+# java-base64++The `java-base64` package installs the `java-base64` Java upatch: an+agent that guards `java.util.Base64$Decoder.decode0` against the x64+AVX-512 tail-underflow of CVE-2026-114938. A crafted input whose length+leaves a one-to-three byte tail with padding can drive the decoder's+native AVX-512 stub to write past the destination array. The agent+rejects that input shape before `decode0` writes, throwing+`IllegalArgumentException` and logging a diagnostic that omits the input+bytes, so a patched JVM is the durable fix and this is a mitigation in+front of it.++The guard is written with the JDK Class-File API alone, with no+third-party dependency. `GuardCheck`, which the instrumented+`java.base` code calls, rides in a nested `guard-check.jar` that the+agent appends to the bootstrap loader when it installs, so the whole+mitigation is one signed jar.++The agent reaches a JVM two ways:++- As a shirudo Java upatch it is applied with `-javaagent` at JVM start,+ through the `JAVA_TOOL_OPTIONS` that+ `/run/environment.d/shirudo.conf` sets (see+ `Documentation/upatches/write/java-agents.rst`). It reaches only JVMs+ that a systemd user manager starts after the upatch is loaded; root+ can start a JVM without it. It is a mitigation inside the application,+ not a boundary against root.+- For a JVM that shirudo does not start, such as the Elasticsearch lab+ below, the same jar attaches to a running process:+ `java -jar java-base64.jar <pid>`.++## Build++The build needs a JDK of release 24 or newer (for the Class-File API),+with `javac` and `jar` on `PATH`:++```sh+upatches/java-base64/build.sh 0.1.0 --keys-dir <keys>+```++It writes `java-base64-0.1.0.bee`. A short version keeps the package's+member paths within the 99 bytes a `.bee` archive allows.++## Publish and view in xtop++`make shields` builds and pushes every shield of `upatches/`, including+this one, to the local stack's registry and loads the catalog, so the+Shields view of `tools/xtop` lists `java-base64` as available, its+`TARGET` the jar it guards and its `FIXES` CVE-2026-114938. Appending it+to a tree with `shirudo bpm tree append` moves it to the "in trees" tab.++## Try it against the Elasticsearch lab++The Elasticsearch compose lab is a JVM that shirudo does not manage, so+xtop shows `java-base64` as a published shield while the lab shows it+applied: copy the signed jar into the container and attach it to the+Elasticsearch JVM. Before, a crafted Base64 request drives the decoder+path; after, the same request gets the guard's rejection. Because the+lab is a container and not a shirudo target, it never reads shirudo's+`environment.d`; the agent is applied by dynamic attach, not by+`-javaagent`.diff --git a/upatches/java-base64/build.sh b/upatches/java-base64/build.shnew file mode 100755index 00000000..4ffcbf4e--- /dev/null+++ b/upatches/java-base64/build.sh@@ -0,0 +1,44 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# Build the Base64 guard agent jar, then the package into the current+# directory:+# upatches/java-base64/build.sh [--jar-only] <version> [bpm build options...]+#+# Needs a JDK of release 24 or newer for the Class-File API (javac and+# jar on PATH). The agent carries GuardCheck in a nested guard-check.jar+# that premain appends to the bootstrap loader, so java.util.Base64 can+# call it; the whole agent is one signed Java upatch.++set -eu++jar_only=0+if [ "${1:-}" = --jar-only ]; then jar_only=1; shift; fi+if [ "$jar_only" -eq 0 ]; then+ [ $# -ge 1 ] || { echo "usage: $0 [--jar-only] <version> [bpm build options...]" >&2; exit 2; }+ version=$1+ shift+fi+pkg=$(cd "$(dirname "$0")" && pwd)++cd "$pkg"+rm -rf target+mkdir -p target/classes target/stage/com/shirudo/base64guard+javac --release 24 -d target/classes src/com/shirudo/base64guard/*.java+# GuardCheck rides alone in a nested jar for the bootstrap loader.+jar cf target/guard-check.jar -C target/classes com/shirudo/base64guard/GuardCheck.class+cp target/classes/com/shirudo/base64guard/Base64GuardAgent*.class \+ target/stage/com/shirudo/base64guard/+cp target/guard-check.jar target/stage/com/shirudo/base64guard/guard-check.jar+cat > target/MANIFEST.MF <<'MF'+Manifest-Version: 1.0+Premain-Class: com.shirudo.base64guard.Base64GuardAgent+Agent-Class: com.shirudo.base64guard.Base64GuardAgent+Main-Class: com.shirudo.base64guard.Base64GuardAgent+Can-Retransform-Classes: true+MF+jar cfm java-base64.jar target/MANIFEST.MF -C target/stage .++[ "$jar_only" -eq 0 ] || exit 0+exec shirudo bpm build "$pkg" --version "$version" "$@"diff --git a/upatches/java-base64/src/com/shirudo/base64guard/Base64GuardAgent.java b/upatches/java-base64/src/com/shirudo/base64guard/Base64GuardAgent.javanew file mode 100644index 00000000..a5fb73cf--- /dev/null+++ b/upatches/java-base64/src/com/shirudo/base64guard/Base64GuardAgent.java@@ -0,0 +1,136 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+package com.shirudo.base64guard;++import com.sun.tools.attach.VirtualMachine;+import java.io.File;+import java.lang.classfile.ClassFile;+import java.lang.classfile.ClassModel;+import java.lang.classfile.ClassTransform;+import java.lang.classfile.CodeBuilder;+import java.lang.classfile.CodeElement;+import java.lang.classfile.CodeTransform;+import java.lang.constant.ClassDesc;+import java.lang.constant.MethodTypeDesc;+import java.lang.instrument.ClassFileTransformer;+import java.lang.instrument.Instrumentation;+import java.lang.reflect.Method;+import java.lang.reflect.Modifier;+import java.security.ProtectionDomain;+import java.util.concurrent.atomic.AtomicBoolean;+import java.io.InputStream;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.StandardCopyOption;+import java.util.jar.JarFile;++/**+ * Prepends a guard to java.util.Base64$Decoder.decode0 that rejects the x64+ * AVX-512 tail-underflow input shape before the vulnerable stub writes out of+ * bounds. Uses only the public Class-File API (no third-party deps). Applies at+ * JVM start through -javaagent (premain) and by dynamic attach (agentmain).+ */+public final class Base64GuardAgent {+ private static final String TARGET = "java/util/Base64$Decoder";+ private static final ClassDesc DECODER = ClassDesc.of("java.util.Base64$Decoder");+ private static final ClassDesc CHECK = ClassDesc.of("com.shirudo.base64guard.GuardCheck");+ private static final CodeTransform PREPEND_GUARD = new CodeTransform() {+ @Override+ public void atStart(CodeBuilder builder) {+ builder.aload(1).iload(2).iload(3)+ .aload(0).getfield(DECODER, "isURL", ClassDesc.ofDescriptor("Z"))+ .aload(0).getfield(DECODER, "isMIME", ClassDesc.ofDescriptor("Z"))+ .invokestatic(CHECK, "check", MethodTypeDesc.ofDescriptor("([BIIZZ)V"));+ }++ @Override+ public void accept(CodeBuilder builder, CodeElement element) {+ builder.with(element);+ }+ };+ private static boolean installed;++ private Base64GuardAgent() {}++ /** Dynamic-attach launcher: java -jar java-base64.jar <pid>. */+ public static void main(String[] args) throws Exception {+ if (args.length != 1) throw new IllegalArgumentException("Usage: java -jar java-base64.jar <pid>");+ VirtualMachine vm = VirtualMachine.attach(args[0]);+ try {+ vm.loadAgent(selfJarPath());+ } finally {+ vm.detach();+ }+ }++ /** -javaagent entry: applies the guard as the JVM starts. */+ public static void premain(String args, Instrumentation instrumentation) throws Exception {+ install(instrumentation);+ }++ /** Dynamic-attach entry: applies the guard to a running JVM. */+ public static void agentmain(String args, Instrumentation instrumentation) throws Exception {+ install(instrumentation);+ }++ private static synchronized void install(Instrumentation instrumentation) throws Exception {+ if (installed) return;+ // java.util.Base64$Decoder is a java.base class, so GuardCheck must be+ // visible to the bootstrap loader for the injected call to resolve.+ // It rides as a nested jar holding GuardCheck alone, so appending it+ // does not also put the agent's own classes on the bootstrap loader.+ appendGuardCheck(instrumentation);+ Class<?> decoder = Class.forName("java.util.Base64$Decoder", false, null);+ Method method = decoder.getDeclaredMethod("decode0", byte[].class, int.class, int.class, byte[].class);+ if (method.getReturnType() != int.class || !Modifier.isPrivate(method.getModifiers())+ || decoder.getDeclaredField("isURL").getType() != boolean.class+ || decoder.getDeclaredField("isMIME").getType() != boolean.class+ || !instrumentation.isRetransformClassesSupported()+ || !instrumentation.isModifiableClass(decoder)) {+ throw new IllegalStateException("Base64.Decoder does not match this guard");+ }+ AtomicBoolean transformed = new AtomicBoolean();+ ClassFileTransformer transformer = new ClassFileTransformer() {+ @Override+ public byte[] transform(ClassLoader loader, String className, Class<?> redefining,+ ProtectionDomain domain, byte[] bytes) {+ if (!TARGET.equals(className)) return null;+ ClassFile cf = ClassFile.of();+ ClassModel model = cf.parse(bytes);+ long matches = model.methods().stream().filter(m -> m.methodName().equalsString("decode0")+ && m.methodType().equalsString("([BII[B)I")).count();+ if (matches != 1) throw new IllegalStateException("decode0 signature changed");+ byte[] result = cf.transformClass(model, ClassTransform.transformingMethodBodies(+ m -> m.methodName().equalsString("decode0") && m.methodType().equalsString("([BII[B)I"),+ PREPEND_GUARD));+ transformed.set(true);+ return result;+ }+ };+ instrumentation.addTransformer(transformer, true);+ try {+ instrumentation.retransformClasses(decoder);+ if (!transformed.get()) throw new IllegalStateException("decode0 was not transformed");+ installed = true;+ System.err.println("Base64 guard installed on java.util.Base64$Decoder.decode0");+ } finally {+ instrumentation.removeTransformer(transformer);+ }+ }++ private static void appendGuardCheck(Instrumentation instrumentation) throws Exception {+ Path jar = Files.createTempFile("shirudo-base64-guard-check", ".jar");+ jar.toFile().deleteOnExit();+ try (InputStream in = Base64GuardAgent.class.getResourceAsStream(+ "/com/shirudo/base64guard/guard-check.jar")) {+ if (in == null) throw new IllegalStateException("guard-check.jar missing from the agent jar");+ Files.copy(in, jar, StandardCopyOption.REPLACE_EXISTING);+ }+ instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(jar.toFile()));+ }++ private static String selfJarPath() throws Exception {+ return new File(Base64GuardAgent.class.getProtectionDomain()+ .getCodeSource().getLocation().toURI()).getAbsolutePath();+ }+}diff --git a/upatches/java-base64/src/com/shirudo/base64guard/GuardCheck.java b/upatches/java-base64/src/com/shirudo/base64guard/GuardCheck.javanew file mode 100644index 00000000..02cfc4bd--- /dev/null+++ b/upatches/java-base64/src/com/shirudo/base64guard/GuardCheck.java@@ -0,0 +1,28 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+package com.shirudo.base64guard;++/** Loaded by the bootstrap loader so java.base can call it from decode0. */+public final class GuardCheck {+ private GuardCheck() {}++ public static void check(byte[] src, int sp, int sl, boolean isURL, boolean isMIME) {+ int length = sl - sp;+ if (isMIME || length < 65) return;+ int remainder = length & 63;+ if (remainder < 1 || remainder > 3) return;+ int padding = 0;+ while (padding < 3 && src[sl - 1 - padding] == '=') padding++;+ if (padding < 1 || padding > 2 || padding > remainder) return;+ for (int i = sp; i < sl - padding; i++) {+ int c = src[i] & 0xff;+ if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')+ || (c >= '0' && c <= '9')+ || (isURL ? c == '-' || c == '_' : c == '+' || c == '/'))) return;+ }+ System.err.println("Base64 guard rejected candidate: length=" + length+ + ", padding=" + padding + ", remainder=" + remainder+ + ", alphabet=" + (isURL ? "URL-safe" : "standard"));+ throw new IllegalArgumentException("Rejected Base64 x64 tail-underflow candidate");+ }+}