Skip to content

eBPF-based security platform

upatch: install, unload and restore Java agents on the target

John Fastabendc7193faabfbc
diff --git a/Documentation/concepts/background/xattrs.rst b/Documentation/concepts/background/xattrs.rst
index 98feb9ae..cd1f9c42 100644
--- a/Documentation/concepts/background/xattrs.rst
+++ b/Documentation/concepts/background/xattrs.rst
@@ -253,8 +253,8 @@ shirudo's seal marks writable state with the xattr
``security.bpf.shirudo``. Its value is a fixed 64-character string, the
same on every target; the seal treats any inode that carries a label
under that name as protected. ``shirudo init`` labels the state tree
-under ``/var/lib/shirudo`` on its first run, and ``/run/shirudo`` on
-every boot. From then on, every inode created in a labeled directory
+under ``/var/lib/shirudo`` on its first run, and ``/run/shirudo`` and
+``/run/shirudo-java`` on every boot. From then on, every inode created in a labeled directory
receives the label as it is created, with ``bpf_inode_init_xattr()``.
The seal's sleepable programs read the label with
diff --git a/Documentation/contribute/testing/proof-coverage.rst b/Documentation/contribute/testing/proof-coverage.rst
index f0a9086f..b5465edd 100644
--- a/Documentation/contribute/testing/proof-coverage.rst
+++ b/Documentation/contribute/testing/proof-coverage.rst
@@ -1346,8 +1346,8 @@ a proof covers.
:src:`util/image_cache.c`, :src:`util/image_config.c`,
:src:`util/image_guards.c`, :src:`util/image_keys.c`,
:src:`util/image_runtime.c`, :src:`util/initrd.c`,
- :src:`util/integrity.c`, :src:`util/keyring.c`,
- :src:`util/preflight.c`, :src:`util/seal.c`,
+ :src:`util/integrity.c`, :src:`util/java_agent.c`,
+ :src:`util/keyring.c`, :src:`util/preflight.c`, :src:`util/seal.c`,
:src:`util/tamper.c`, :src:`util/upatch_maps.c`,
:src:`util/upatch_pins.c`, :src:`util/upatch_resolve.c`,
:src:`util/upatch_verify.c`, :src:`util/xdp.c`
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rst
index 8fca7aba..ca7521da 100644
--- a/Documentation/contribute/testing/test-coverage.rst
+++ b/Documentation/contribute/testing/test-coverage.rst
@@ -270,6 +270,18 @@ signed config image.
- Live ``kprobe.multi`` and ``kretprobe.multi`` links attach to two
functions, run on entry and return, report their kind and count,
unload cleanly, and reject a missing target
+ * - ``t3114-java-agent``
+ - A Java load under a umask of ``077`` writes the jar sealed,
+ readable by an unprivileged user and unchangeable by root, in a
+ directory root cannot move while the state root stays ``0700``,
+ names it in ``JAVA_TOOL_OPTIONS`` in a ``0644`` file of a ``0755``
+ directory, measures a ``java_load`` that ``status``
+ counts as in place and lists with the location ``java``, and
+ refuses a second load; one signed by a key
+ not enrolled, one relabelled BPF with a loader its header bounds
+ admit, and a BPF unload directive that names the agent are
+ refused; the unload removes options and archive, measures a
+ ``java_unload`` and leaves a jar whose agent does nothing
``tpm`` (4)
~~~~~~~~~~~
@@ -816,13 +828,14 @@ signed config image.
Unit suites and fuzz targets
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-The unit suites in :src:`testing/unit/` cover 32 of the modules in
+The unit suites in :src:`testing/unit/` cover 34 of the modules in
:src:`util/`: ``attest``, ``bpm_oci``, ``bpm_package``, ``bpm_state``,
``bpm_tree``, ``bpm_tree_overlap``, ``bpm_tree_state``, ``chain``,
``chain_history``, ``conditions``, ``crypto_openssl``,
-``eventlog``, ``format``, ``hex``, ``io``, ``json``, ``kernel_abi``,
+``eventlog``, ``format``, ``hex``, ``io``, ``java_agent``, ``json``,
+``kernel_abi``,
``keepalive``, ``keepalive_quote``, ``kernel_build_id``,
-``kernel_release``, ``measured``, ``options``,
+``kernel_release``, ``keys``, ``measured``, ``options``,
``paths``, ``string``, ``sysinfo``, ``upatch``, ``upatch_decode``,
``upatch_pins``, ``upatch_resolve``, ``upatch_verify`` and ``xdp``, and
``overflow`` the arithmetic of
diff --git a/Documentation/internals/architecture.rst b/Documentation/internals/architecture.rst
index 61e77868..6c9a0efa 100644
--- a/Documentation/internals/architecture.rst
+++ b/Documentation/internals/architecture.rst
@@ -22,7 +22,10 @@ operator installed without a record, or rewrite the record. Root can issue
every system call, so none of these properties can rest on a userspace
process that root could stop, trace or bypass. We put each decision into
the kernel, on the call that changes state, and keep the userspace part
-small, short-lived and verified at boot.
+small, short-lived and verified at boot. A Java upatch is the one
+exception: a JVM, not the kernel, loads its jar, so its signature is
+checked in userspace, and it is a mitigation in the JVMs it reaches, not
+a boundary against root (:doc:`/security/threat-model`, R24).
The operator side has the opposite problem. It holds the only secret, the
ML-DSA-87 signing key, and it must not need any state about the targets,
diff --git a/Documentation/internals/boot-flow.rst b/Documentation/internals/boot-flow.rst
index a8ed3f6a..93b02087 100644
--- a/Documentation/internals/boot-flow.rst
+++ b/Documentation/internals/boot-flow.rst
@@ -60,6 +60,9 @@ the switch to the root file system. It needs
#. Create ``/run/shirudo``, mount a private tmpfs there when it is still
part of ``/run``, label it, and mount the private bpffs at
``/run/shirudo/bpffs`` with ``mode=0700,nosuid,nodev,noexec``.
+#. Create ``/run/shirudo-java`` with mode ``0755`` and label it, or check
+ that the one there is root's and labeled: boot restore writes the
+ jars of the Java upatches there, where every JVM can read them.
#. Map the runtime image with dm-verity, check its root hash against
``runtime.root_hash``, read the whole mapping, mount it and read the
runtime's bootstrap settings: ``config.image``,
diff --git a/Documentation/internals/kernel-interfaces.rst b/Documentation/internals/kernel-interfaces.rst
index 8601db65..dae385a0 100644
--- a/Documentation/internals/kernel-interfaces.rst
+++ b/Documentation/internals/kernel-interfaces.rst
@@ -302,7 +302,8 @@ Extended attributes
* - Name
- Use
* - ``security.bpf.shirudo``
- - The seal label on writable state and on ``/run/shirudo``.
+ - The seal label on writable state, on ``/run/shirudo`` and on
+ ``/run/shirudo-java``.
* - ``security.bpf.shirudo.payload``
- The 32-byte payload digest on each upatch's pin directory in the
private bpffs.
diff --git a/Documentation/internals/seal.rst b/Documentation/internals/seal.rst
index 5ca577f9..497ab7db 100644
--- a/Documentation/internals/seal.rst
+++ b/Documentation/internals/seal.rst
@@ -214,7 +214,9 @@ attached, ``init`` refuses a state root without a label, because that is
a tree bound over the path rather than the one it sealed.
``init`` also labels ``/run/shirudo``, so that the init record it leaves
-there for the root file system is sealed from its creation. The runtime
+there for the root file system is sealed from its creation, and
+``/run/shirudo-java``, the one sealed directory every user may read,
+which holds the jars of the Java upatches. The runtime
and config images carry no labels; dm-verity protects them.
What the seal checks
diff --git a/Documentation/internals/signed-loader.rst b/Documentation/internals/signed-loader.rst
index 240672ba..e3f81423 100644
--- a/Documentation/internals/signed-loader.rst
+++ b/Documentation/internals/signed-loader.rst
@@ -17,11 +17,17 @@ the mechanism stops.
Problem
-------
-Every upatch is BPF, so shirudo cannot switch BPF off. It needs a kernel
+Upatches are BPF, so shirudo cannot switch BPF off. It needs a kernel
that accepts BPF the operator signed and refuses BPF from anyone else,
root with every capability included. Root can issue any system call, so
the decision has to sit where root cannot step around it.
+A Java upatch is the exception: it carries a jar and no loader, so it
+never takes this path. The target checks its signature in userspace, as
+the Java payloads section of :doc:`/reference/formats/upatch-format`
+describes, and :doc:`/security/threat-model` (T15, R24) says why that
+makes it a mitigation and not a boundary against root.
+
Why a check in userspace fails
------------------------------
diff --git a/Documentation/operate/run/read-status.rst b/Documentation/operate/run/read-status.rst
index d8e5a628..f0e6982b 100644
--- a/Documentation/operate/run/read-status.rst
+++ b/Documentation/operate/run/read-status.rst
@@ -280,7 +280,8 @@ The details other than ``OK`` are below, with what each means.
<names>``
- What a load stopped between its pins and its extend leaves, or an
archive root brought back after its unload. The next ``upatch
- load`` or ``upatch unload`` undoes them before it acts.
+ load`` or ``upatch unload`` undoes them before it acts. The count
+ includes the jar of a Java agent that no archive backs.
* - ``UpatchesMeasured``
- ``ALERT``
- ``<n> XDP archives differ from the loaded payload: <names>``
@@ -421,7 +422,8 @@ Loaded upatches
One row per upatch pinned in the private bpffs: its name, the attach
location resolved from kernel BTF, its number of maps, ``success`` and
-the time since it was loaded. ``Loaded upatches (0):`` followed by
+the time since it was loaded. A loaded Java agent follows them with the
+location ``java`` and no maps. ``Loaded upatches (0):`` followed by
``none`` means nothing is loaded.
TPM measurement
diff --git a/Documentation/reference/cli/build.rst b/Documentation/reference/cli/build.rst
index 0e3919f0..26df6fd3 100644
--- a/Documentation/reference/cli/build.rst
+++ b/Documentation/reference/cli/build.rst
@@ -102,6 +102,7 @@ artifact carries no loader: its data holds the signed name, the payload
type and the jar, and the detached CMS signature covers that data alone
(see the Java payloads of :doc:`/reference/formats/upatch-format`).
The helper prints ``wrote <output> (java sig=<n> data=<n> name=<name>)``.
+:doc:`/upatches/write/java-agents` describes what a target does with it.
Signing an unload directive
~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/Documentation/reference/cli/upatch-list.rst b/Documentation/reference/cli/upatch-list.rst
index ec3c04c3..d3aae839 100644
--- a/Documentation/reference/cli/upatch-list.rst
+++ b/Documentation/reference/cli/upatch-list.rst
@@ -30,8 +30,10 @@ Description
``/run/shirudo/bpffs/upatches/``:
- one row per archived artifact: its name, ``LOADED`` ``yes`` or
- ``no``, its type (``load`` or ``unload``), its payload kind and the
- first 16 hexadecimal characters of its payload digest
+ ``no``, its type (``load`` or ``unload``), its payload kind (``bpf``
+ or ``java``) and the first 16 hexadecimal characters of its payload
+ digest. A Java upatch is loaded while its installed jar is the
+ archived one.
- one row per pinned upatch without an archive copy, marked
``not archived, gone at reboot``
diff --git a/Documentation/reference/cli/upatch-load.rst b/Documentation/reference/cli/upatch-load.rst
index bb393064..562f3ce0 100644
--- a/Documentation/reference/cli/upatch-load.rst
+++ b/Documentation/reference/cli/upatch-load.rst
@@ -54,8 +54,9 @@ Description
only the records the register vouches for, which fold to the value
the TPM reports, and refuses (``tampered``) when they do not, and
(``tpm_error``) when it cannot read this boot's records or cannot
- undo one of them. A upatch of the same name that is loaded is
- refused (``already_loaded``).
+ undo one of them. A upatch of the same name that is loaded, BPF or
+ Java, is refused (``already_loaded``), a Java one also when its jar
+ is missing or another, until its signed directive unloads it.
#. It parses the artifact: a LOAD artifact, a safe and signed name, a
payload digest that matches the payload, valid attach metadata
(``parser_rejected``). For a uprobe it checks each target binary
@@ -76,8 +77,19 @@ Description
payload digest, and appends the event to the eventlog (``tpm_extend``
phase).
+A Java upatch (see :doc:`/upatches/write/java-agents`) takes these steps
+in place of loading, running and attaching a loader: ``load`` checks its
+signature over the signed data against the certificates of the
+runtime that the ``.bpf`` keyring holds (``java_verify`` phase,
+``signature_rejected``), and its signed name, type and payload digest
+(``parser_rejected``), then writes its jar
+to ``/run/shirudo-java/<name>.jar`` (``java_install`` phase). It
+archives and extends as above, with the ``java_load`` event, then
+rewrites ``/run/environment.d/shirudo.conf``. A failure to write that
+file is a warning: the upatch is loaded and measured.
+
When the copy to the archive or the register extend fails, ``load``
-removes the pins and the archive again, so that no upatch runs
+removes the pins or the jar and the archive again, so that no upatch runs
unmeasured. When the extend succeeded and only the eventlog append failed,
the upatch stays loaded and the report says ``tpm_error``. A ``load``
stopped between its pins and its extend leaves the pins: ``status``
diff --git a/Documentation/reference/cli/upatch-unload.rst b/Documentation/reference/cli/upatch-unload.rst
index 4f59c21f..7d4e6f4b 100644
--- a/Documentation/reference/cli/upatch-unload.rst
+++ b/Documentation/reference/cli/upatch-unload.rst
@@ -51,9 +51,10 @@ both in signed sections (see :doc:`build`). ``unload``:
digest that cannot be read, is refused with ``payload_mismatch``. A
directive signed with an all-zero digest never matches.
#. When the upatch has no pin, it removes the archive copy if it holds
- the directive's payload, reports ``already_unloaded`` and exits with
- 0 without measuring. An archive of another payload stays, and the
- unload is refused with ``payload_mismatch``.
+ the directive's payload and is a BPF upatch, reports
+ ``already_unloaded`` and exits with 0 without measuring. An archive of
+ another payload or of a Java upatch stays, and the unload is refused
+ with ``payload_mismatch``.
#. It extends the register with the ``upatch_unload`` event and appends
it to the eventlog. The event comes first: a failed extend leaves the
upatch attached.
@@ -62,6 +63,20 @@ both in signed sections (see :doc:`build`). ``unload``:
removed after the event was measured, the report says
``detach_failed``. Repeat the unload.
+The directive of a Java upatch (see :doc:`/upatches/write/java-agents`)
+has no loader. ``unload`` checks its signature over the signed data
+against the certificates of the ``.bpf`` keyring (``java_verify``
+phase), and refuses with ``payload_mismatch`` unless the archive is the
+Java upatch with the directive's payload. Without an archive it reports
+``already_unloaded``. It then extends the register with the
+``java_unload`` event, replaces ``/run/shirudo-java/<name>.jar`` with a
+jar whose agent does nothing, removes the archive, and rewrites
+``/run/environment.d/shirudo.conf``. The jar stays until the next boot:
+a user manager started before the unload still names it in
+``JAVA_TOOL_OPTIONS``, and a JVM does not start when a ``-javaagent``
+jar is missing. A BPF unload directive that names a Java upatch is
+refused with ``payload_mismatch``.
+
An unload moves the register forward. It never returns the register to
the value it had before the load.
diff --git a/Documentation/reference/failure-categories.rst b/Documentation/reference/failure-categories.rst
index aa0be870..a5b9b6b0 100644
--- a/Documentation/reference/failure-categories.rst
+++ b/Documentation/reference/failure-categories.rst
@@ -45,8 +45,8 @@ the rest of the artifact in ``parse``, and then goes from
data, and the signed attach metadata.
* - ``pin``
- Load: refusing a name that is loaded. Unload: comparing the
- payload recorded on the pin directory with the directive's, and
- removing the pins.
+ payload recorded on the pin directory, or the archive of a Java
+ upatch, with the directive's, and removing the pins or the jar.
* - ``target_verify``
- Opening each ``uprobe``, ``uretprobe``, ``uprobe.multi`` and
``uretprobe.multi`` target binary and comparing its GNU build ID
@@ -55,6 +55,15 @@ the rest of the artifact in ``parse``, and then goes from
- Creating, filling and freezing ``__loader.map`` and the
``BPF_PROG_LOAD`` of the signed loader, where the kernel verifies
the signature against the ``.bpf`` keyring.
+ * - ``java_verify``
+ - A Java upatch only, in place of ``signed_loader_load``: its signed
+ name, type and payload digest, and its signature over the signed
+ data against the certificates of the runtime that the ``.bpf``
+ keyring holds.
+ * - ``java_install``
+ - A Java load only, in place of ``payload_load`` and
+ ``link_create``: writing the jar to
+ ``/run/shirudo-java/<name>.jar``.
* - ``payload_load``
- ``BPF_PROG_TEST_RUN`` of the loader, which loads the payload
programs and maps through the verifier.
@@ -132,7 +141,7 @@ Categories
:doc:`/reference/configuration`. The eventlog is sealed
and cannot be rotated.
* - ``parser_rejected``
- - ``parse``, ``target_verify``
+ - ``parse``, ``target_verify``, ``java_verify``
- - The artifact cannot be read or is malformed: the errno of the
read.
- Wrong kind (a directive given to ``load`` or the reverse),
@@ -187,8 +196,9 @@ Categories
while it was opened, or its build ID differs from the recorded one.
- Rebuild the upatch against the installed binary.
* - ``signature_rejected``
- - ``signed_loader_load``
- - ``EKEYREJECTED``. The kernel rejected the loader's signature.
+ - ``signed_loader_load``, ``java_verify``
+ - ``EKEYREJECTED``. The kernel rejected the loader's signature, or
+ no enrolled certificate verifies a Java upatch's signature.
- Fetch or rebuild the artifact. Check that the file was not
modified after signing.
* - ``signature_unsupported``
@@ -268,8 +278,8 @@ Categories
``tampered``; handle that as an incident.
* - ``unknown``
- ``pre_flight``, ``parse``, ``target_verify``,
- ``signed_loader_load``, ``payload_load``, ``link_create``,
- ``persist``, ``pin``
+ ``signed_loader_load``, ``java_verify``, ``java_install``,
+ ``payload_load``, ``link_create``, ``persist``, ``pin``
- The errno of the call. Any other failure: out of memory, a failed
hash of the loader, an unclassified attach error, a payload that
cannot be recorded on the pin directory or a failed archive copy
diff --git a/Documentation/reference/files.rst b/Documentation/reference/files.rst
index 150d0d96..7c5c229c 100644
--- a/Documentation/reference/files.rst
+++ b/Documentation/reference/files.rst
@@ -253,6 +253,23 @@ carries ``/run`` from the initrd into the root file system.
- dm-verity
- A config image being activated. Its mapping is
``shirudo-config-<root-hash>``.
+ * - ``/run/shirudo-java/<name>.jar``
+ - ``upatch load``, ``init``
+ - seal, ``0644`` in a ``0755`` directory
+ - The agent jar of a loaded Java upatch, readable by every JVM.
+ ``init`` makes and labels the directory, and writes each jar
+ from its archive at boot. An unload, a purge and every upatch
+ command replace a jar whose archive is not a Java load with one
+ whose agent does nothing, which stays until the next boot.
+ * - ``/run/environment.d/shirudo.conf``
+ - ``upatch load``, ``upatch unload``, ``init``
+ - none, ``0644``
+ - A ``-javaagent`` for each jar in ``/run/shirudo-java`` whose
+ archive is a Java load, in name order, appended to
+ ``JAVA_TOOL_OPTIONS``. Rewritten only when that changes it, and
+ removed when there is none. It lasts as long as the jars it names. Root can change it.
+ systemd's user managers read it; see
+ :doc:`/upatches/write/java-agents`.
Runtime image
~~~~~~~~~~~~~
@@ -415,7 +432,7 @@ Extended attributes
- Value and rules
* - ``security.bpf.shirudo``
- Every regular file and directory of shirudo's writable state:
- ``/var/lib/shirudo``, ``/run/shirudo``.
+ ``/var/lib/shirudo``, ``/run/shirudo``, ``/run/shirudo-java``.
- 64 lowercase hex characters, the SHA-256 of the attribute name,
the same on every build. The seal treats any value as the label.
Only a task with runtime authority may set it (``SealLabel``).
diff --git a/Documentation/reference/formats/keepalive.rst b/Documentation/reference/formats/keepalive.rst
index 72c93f2b..f0096e78 100644
--- a/Documentation/reference/formats/keepalive.rst
+++ b/Documentation/reference/formats/keepalive.rst
@@ -339,8 +339,9 @@ upatch or a thousand.
- hash
- SHA-256 over a ``<payload_sha256> <name>`` line for every loaded
upatch, sorted by name: the ``set_digest`` form of the ``init``
- event (:doc:`/reference/eventlog`). Upatches loaded outside the
- tree are included.
+ event (:doc:`/reference/eventlog`), without the ``java`` prefix
+ that event gives a Java upatch, as a tree operation names no
+ payload type. Upatches loaded outside the tree are included.
* - ``count``
- integer
- The upatches loaded.
diff --git a/Documentation/reference/formats/status-json.rst b/Documentation/reference/formats/status-json.rst
index b29d8abc..230f3001 100644
--- a/Documentation/reference/formats/status-json.rst
+++ b/Documentation/reference/formats/status-json.rst
@@ -119,7 +119,8 @@ determined, as noted.
* - ``upatches_loaded``
- array of object
- One object per upatch pinned under
- ``/run/shirudo/bpffs/upatches``, see `upatches_loaded`_.
+ ``/run/shirudo/bpffs/upatches``, then one per loaded Java agent,
+ see `upatches_loaded`_.
* - ``assets``
- object
- Persistent state, see `assets`_.
@@ -472,7 +473,8 @@ upatches_loaded
- The upatch name.
* - ``location``
- string
- - The attach point, for example ``fentry/do_nanosleep``.
+ - The attach point, for example ``fentry/do_nanosleep``; ``java``
+ for a Java agent.
* - ``status``
- string
- ``success``
@@ -481,7 +483,8 @@ upatches_loaded
- Maps pinned for the upatch.
* - ``loaded_at``
- string
- - Change time of the upatch's pin directory, ISO 8601 UTC.
+ - Change time of the upatch's pin directory, or of a Java agent's
+ jar, ISO 8601 UTC.
* - ``age_sec``
- integer or ``null``
- Seconds since ``loaded_at``.
diff --git a/Documentation/reference/formats/upatch-format.rst b/Documentation/reference/formats/upatch-format.rst
index 50450080..66f602c9 100644
--- a/Documentation/reference/formats/upatch-format.rst
+++ b/Documentation/reference/formats/upatch-format.rst
@@ -338,9 +338,11 @@ loader. It has no loader instructions and no ``metadata``, and
``loader_insns_off``, ``log_buf_sz``, ``nr_maps``, ``nr_progs`` and
``rodata_data_off`` are 0. Its ``data`` holds only signed sections, so the
signature covers ``data`` alone and ``payload_sha256`` is SHA-256 of
-``data``. The kernel never sees a Java payload: the target verifies its
-signature in userspace against the certificates the sealed ``.bpf`` keyring
-was enrolled from.
+``data``. The kernel never sees a Java payload. The target verifies its
+signature in userspace with OpenSSL, against the unrevoked certificates of
+the authenticated runtime's set, and then requires the signer to be a key
+the sealed ``.bpf`` keyring holds. That lookup compares the description the
+kernel gives the key, not the key material.
The header is not signed, so the signed ``PTYP`` section carries the type
too, and the reader refuses a file whose header ``type`` differs from it. A
@@ -837,6 +839,16 @@ of checks 1 to 7 is reported as ``parser_rejected``, see
equals the recorded one.
#. The kernel verifies the signature in ``BPF_PROG_LOAD``.
+A Java load artifact passes the reader, then, in place of the checks
+above: ``flags`` bit 0 is clear, the name is as in check 4, ``NAME``,
+``PTYP`` and ``JAVA`` are present, ``NAME`` equals the header ``name``,
+``PTYP`` is 2, ``payload_sha256`` equals SHA-256 of ``data``
+(``parser_rejected``), and the signature verifies over ``data`` under a
+certificate ``init`` enrolled in the ``.bpf`` keyring
+(``signature_rejected``). A Java unload directive takes the same checks
+with ``UNLD`` in place of ``JAVA`` and bit 0 set. See
+:doc:`/upatches/write/java-agents`.
+
An unload directive passes the reader, then these checks:
#. ``flags`` bit 0 is set.
diff --git a/Documentation/security/cryptography.rst b/Documentation/security/cryptography.rst
index 7f4e4829..980d86e4 100644
--- a/Documentation/security/cryptography.rst
+++ b/Documentation/security/cryptography.rst
@@ -93,6 +93,10 @@ verifies:
algorithm. The pre-flight check ``cert_algorithm`` refuses
anything but ML-DSA-87, but in the initrd it reads
``/etc/shirudo/keys``, not that set (threat model U4).
+ * - Target, Java upatch signatures
+ - Any algorithm OpenSSL supports for a certificate of the runtime's
+ set that ``.bpf`` holds, as for the kernel's check of a loader
+ (threat model T15).
* - Target, config roots
- ML-DSA-87 under one of the runtime bootstrap's config certificates.
The target checks this exact set before the kernel's dm-verity
diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rst
index dcb3948a..e5930a7c 100644
--- a/Documentation/security/threat-model.rst
+++ b/Documentation/security/threat-model.rst
@@ -44,7 +44,7 @@ Every entry has a stable ID that commits, issues and other pages cite:
- Residual risks: known and bounded limits of the mechanisms.
* - U1 to U20
- Threats to resolve: gaps in the code that are not closed yet.
- * - D1 to D9
+ * - D1 to D10
- Deferred mitigations that are in scope.
Each threat is explained in prose and then summarized in a fact box.
@@ -1505,6 +1505,62 @@ driver; sessions do not prevent denial of service by dropping requests.
:Proofs: ``tpm-public``, ``tpm-kdf``
:Residual: trusted bootstrap (A1, A6, A8); denial of service
+T15 Installing an unsigned Java agent
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+A Java upatch installs a jar that every JVM started with shirudo's
+options loads as an agent, with the JVM's privileges. Root who could
+install a jar of its own there, change the installed one, or have a BPF
+artifact taken for a Java one, or the reverse, would run code the
+operator never signed under a name the register records as signed.
+
+No kernel check covers a Java upatch: it has no loader. ``upatch load``
+and boot restore check its signature over the signed data in userspace
+with OpenSSL, against the unrevoked certificates of the authenticated
+runtime's set, then require the signer to be a key the ``.bpf`` keyring
+holds, found by the description the kernel gives the key, not by its
+material. Config activation already refuses a set the keyring does not
+hold, so the lookup keeps the Java check from resting on that alone. A
+key a revocation unlinked signs no Java upatch, as it signs no BPF one;
+a key a later config drops without revoking it stays in the ring and
+still signs a BPF upatch, but no Java one. They also check its signed
+name, signed type and payload digest. The header's type is not signed,
+so the reader refuses a file whose type differs from the signed ``PTYP``
+section; a BPF artifact carries none and cannot be relabelled Java. A
+Java artifact relabelled BPF is refused by that check too. The two
+signatures cover one byte stream under one key with no type in it,
+though: signed Java data split into a loader and data of another
+length loses its section directory, reads as BPF, and is then refused
+only because it has no signed name and its bytes are no loader the
+verifier accepts (D10). The jar is written
+sealed under ``/run/shirudo-java``, which ``init`` makes and labels
+before anyone else can, outside the state root, which stays ``0700``.
+The seal refuses a write, rename, unlink or label change of the jar, and
+the removal of its directory, to every task without runtime authority.
+Boot restore writes the jar from the archive at each boot, and a later
+run of ``init`` in the same boot refuses a jar that is missing or
+another rather than writing it again, which would hide that JVMs started
+without it. An unload or a purge leaves a jar in its place whose agent
+does nothing, which is part of the shirudo binary and stays until the
+next boot, so that a JVM whose options still name the jar starts. Its
+load and unload are measured as ``java_load`` and
+``java_unload`` events, which no BPF event can be read as, and
+``status`` reports a measured agent whose jar is missing or another.
+
+.. rst-class:: facts
+
+:Adversary: ADV-B, root on the target without the signing key
+:Enforced at: ``java_upatch_verify()`` and the reader's type check in
+ userspace; ``lsm.s/file_open`` and the seal's inode hooks for the jar
+:Refusal: ``signature_rejected`` or ``parser_rejected``; ``EACCES`` on
+ the jar
+:Counters: ``SealWrite``, ``SealUnlink``, ``SealRename``, ``SealSetattr``,
+ ``SealXattr`` for the jar; none for a refused load
+:Tests: ``t3014``, ``t3114``
+:Proofs: ``upatch-header``, ``upatch-signed-sections``, ``chain-events``,
+ ``Shirudo.Events``
+:Residual: R2, R24
+
Residual risks
--------------
@@ -1857,6 +1913,21 @@ R23 Policy labels follow the inode
reloads after a change to a labeled path. Detection: none on the
target.
+R24 A Java agent reaches only the JVMs its options reach
+ The options that name the agents are
+ ``/run/environment.d/shirudo.conf``, which is not sealed, and which
+ systemd's user managers read. Root can change or remove it, set
+ ``JAVA_TOOL_OPTIONS`` for a JVM of its own, or start one without a
+ user manager, and a JVM running when the agent loads keeps the agents
+ it started with. A user manager reads the options when it starts: one
+ started before a load starts its JVMs without the agent until it
+ restarts, and another ``environment.d`` file can set
+ ``JAVA_TOOL_OPTIONS`` over shirudo's. An agent is Java code in the JVM it guards, which
+ the application can undo. A Java upatch is therefore a mitigation in
+ the applications that start with it, not a boundary against root,
+ which only a BPF upatch is. Detection: a JVM's ``-javaagent``
+ arguments, ``jcmd <pid> VM.command_line``; none from shirudo.
+
Threats to resolve
------------------
@@ -2103,6 +2174,12 @@ D9 Perf events across exec
that marks it (T3), tracked in `issue 11
<https://github.com/shirudo-dev/shirudo/issues/11>`__.
+D10 A payload type in the signed message
+ Sign the payload type with the loader and the data, so that a
+ signature made for a Java upatch verifies for nothing a BPF header
+ can describe, and the reverse, without resting on the signed
+ sections that follow (T15).
+
Out of scope
------------
diff --git a/Documentation/upatches/write/index.rst b/Documentation/upatches/write/index.rst
index 389e50ae..54331633 100644
--- a/Documentation/upatches/write/index.rst
+++ b/Documentation/upatches/write/index.rst
@@ -8,7 +8,8 @@ Write
Where a program can attach, how a upatch keeps and exports its state in
maps, arenas and serializers, how a Lua decoder turns that state into
telemetry, what a program can miss or cannot rely on, and how to test
-the memory ordering that programs on several CPUs rely on.
+the memory ordering that programs on several CPUs rely on. It also
+covers how a Java agent ships as an upatch.
.. toctree::
:titlesonly:
@@ -17,4 +18,5 @@ the memory ordering that programs on several CPUs rely on.
maps-arenas-serializers
decoders
pitfalls
+ java-agents
memory-consistency/index
diff --git a/Documentation/upatches/write/java-agents.rst b/Documentation/upatches/write/java-agents.rst
new file mode 100644
index 00000000..ebd9bc6c
--- /dev/null
+++ b/Documentation/upatches/write/java-agents.rst
@@ -0,0 +1,101 @@
+..
+ SPDX-License-Identifier: BSD-2-Clause
+ Copyright (c) 2026 Authors of shirudo
+
+:page-type: Explanation
+:audience: upatch authors, operators, security reviewers
+
+Java agent upatches
+===================
+
+A Java agent upatch ships a ``java.lang.instrument`` agent, a ``.jar``
+with a ``Premain-Class`` in its manifest, the way a BPF upatch ships a
+program: signed by the operator, loaded and unloaded by signed
+artifacts, measured into the register and restored at boot. What it
+patches is the JVMs that load the agent, not the kernel.
+
+Build and ship
+--------------
+
+``shirudo build agent.jar`` signs the jar into ``agent.upatch``, and
+``shirudo build --unload agent`` signs its directive (see
+:doc:`/reference/cli/build`). In a package, a Beefile upatch with
+``type = "java"`` and a ``.jar`` source does the same (see
+:doc:`/reference/formats/beefile`). The container carries no loader: its
+signed data holds the name, the payload type and the jar
+(:doc:`/reference/formats/upatch-format`).
+
+The jar must name a ``Premain-Class`` in its manifest, and with its
+signature fit the 16 MiB a ``.upatch`` may have; ``build`` refuses one
+that does not.
+
+On the target
+-------------
+
+``shirudo upatch load agent.upatch``, or a ``bpm install`` of the
+package:
+
+#. checks the signature over the signed data against the certificates
+ of the authenticated runtime that the ``.bpf`` keyring holds, as the
+ kernel does for a BPF loader, and the signed name, payload type and
+ payload digest;
+#. writes the jar, sealed, to ``/run/shirudo-java/agent.jar``, mode
+ ``0644``, archives the upatch and measures a ``java_load`` event;
+#. writes ``/run/environment.d/shirudo.conf`` with one
+ ``-javaagent:/run/shirudo-java/<name>.jar`` for each loaded Java
+ upatch, in name order, appended to the ``JAVA_TOOL_OPTIONS`` that
+ ``environment.d`` files sorting before it set.
+
+``shirudo upatch unload agent.unload.upatch`` measures a ``java_unload``
+event, replaces the jar with one whose agent does nothing, removes the
+archive, and rewrites the options without the agent. At boot ``init``
+verifies each archived Java upatch the eventlog records as loaded and
+writes its jar and the options, which ``/run`` carries to the root file
+system. A later run of ``init`` in the same boot leaves a jar that is
+the archived one in place, and refuses one that is missing or another as
+tampered, as it refuses a BPF upatch without its pins. ``upatch list``
+and ``status`` show a Java
+upatch loaded while its installed jar is the archived one; ``status``
+reports one whose jar is missing or another under ``UpatchesMeasured``,
+and a jar no archive backs, which a load stopped before its archive
+leaves until the next upatch command replaces it.
+
+A BPF and a Java upatch share one name space: a load is refused as
+``already_loaded`` when a upatch of either kind is loaded under its name.
+
+What reaches a JVM
+------------------
+
+The seal keeps the jar as signed: no task without runtime authority can
+write, rename or remove it. The options file is not sealed, and what
+reads it is outside shirudo:
+
+- systemd's user managers read ``environment.d`` and pass the options
+ to the JVMs they start. A system service, a container or a login that
+ no user manager starts does not see them; such a JVM needs the same
+ ``-javaagent`` in its own unit or command line.
+- A JVM reads ``JAVA_TOOL_OPTIONS`` when it starts. One already running
+ keeps the agents it started with until it restarts.
+- A user manager reads ``environment.d`` when it starts. One started
+ before a load does not name the agent in the JVMs it starts, and one
+ started before an unload still names it. A JVM does not start when a
+ ``-javaagent`` jar is missing, so an unload leaves a jar in place whose
+ agent does nothing, until the next boot.
+- An ``environment.d`` file that sorts after ``shirudo.conf`` and sets
+ ``JAVA_TOOL_OPTIONS`` without ``${JAVA_TOOL_OPTIONS}`` in its value
+ drops the agents.
+- Root, or the user who starts the JVM, can set ``JAVA_TOOL_OPTIONS`` or
+ edit the file, and so start a JVM without the agent.
+- A Java 8 JVM reads at most 1024 bytes and 64 options from
+ ``JAVA_TOOL_OPTIONS`` and drops options past that without an error
+ (JDK-8288483). Each agent adds ``-javaagent:/run/shirudo-java/<name>.jar``
+ to what other ``environment.d`` files set, so keep the agents few and
+ their names short where Java 8 runs.
+
+An agent does what Java code in the JVM can do: it is a mitigation
+inside the application, not a boundary the kernel enforces. A BPF upatch
+is the tool for a policy that root must not be able to step around.
+
+A Java agent cannot report to a BPF upatch: the BPF LSM refuses
+``BPF_OBJ_GET`` and ``BPF_PROG_TEST_RUN`` to every task but shirudo, so
+an agent's telemetry goes through the JVM's own logging.
diff --git a/Makefile.shirudo b/Makefile.shirudo
index f3f10146..41ba64f2 100644
--- a/Makefile.shirudo
+++ b/Makefile.shirudo
@@ -235,6 +235,7 @@ UTIL_SRCS := \
util/upatch.c \
util/xdp.c \
util/measured.c \
+ util/java_agent.c \
util/keyring.c \
util/keys.c \
util/identity.c \
@@ -1289,8 +1290,9 @@ $(FUZZ_OUT)/fuzz-upatch-info: testing/fuzz/fuzz-upatch-info.c $(FUZZ_BASE) \
builtin.h util/chain.c util/crypto_openssl.c \
util/curl.c util/elf_target.c util/eventlog.c \
util/help.c util/identity.c util/initrd.c \
- util/io.c util/kernel_abi.c util/keyring.c \
- util/measured.c util/nv_writer.c \
+ util/io.c util/java_agent.c util/kernel_abi.c \
+ util/keyring.c util/keys.c util/measured.c \
+ util/nv_writer.c \
util/options.c util/paths.c util/report.c \
util/serializer.c util/similar.c \
util/timefmt.c util/tls_openssl.c util/tpm.c \
diff --git a/builtin-init.c b/builtin-init.c
index 7a68b26d..a0b318f9 100644
--- a/builtin-init.c
+++ b/builtin-init.c
@@ -42,6 +42,7 @@
#include "util/identity.h"
#include "util/initrd.h"
#include "util/io.h"
+#include "util/java_agent.h"
#include "util/image_config.h"
#include "util/image_guards.h"
#include "util/image_runtime.h"
@@ -984,6 +985,40 @@ static int init_lsm(void)
#define HEXLEN(n) ((n) * 2 + 1)
+/*
+ * A Java upatch is in place when its jar is the archived one. Once the
+ * register was bound this boot a missing or other jar is refused, as a
+ * BPF upatch without its pins is: JVMs may have started without the agent
+ * meanwhile, which writing the jar again would hide.
+ */
+static int java_restore(const char *name, const char *path, bool recorded)
+{
+ __u8 payload[UPATCH_PAYLOAD_HASH_LEN];
+ int ret;
+
+ ret = java_agent_payload(name, payload);
+ if (!ret) {
+ pr_info("boot-restore: %s already installed", name);
+ return 0;
+ }
+ if (ret != -ESTALE) {
+ pr_err("boot-restore: cannot tell whether %s is installed: %s",
+ name, strerror(-ret));
+ return ret;
+ }
+ if (recorded) {
+ pr_err("boot-restore: the jar of %s is missing or another "
+ "after the register was bound this boot (tampered); "
+ "unload it or reboot", name);
+ return -EPERM;
+ }
+ if (upatch_restore(path) != 0) {
+ pr_err("boot-restore: failed to install %s", name);
+ return -EINVAL;
+ }
+ return 0;
+}
+
/*
* All or nothing: one failure leaves init incomplete and the register
* unextended. The eventlog says which archives are shirudo's to
@@ -1080,6 +1115,12 @@ static int boot_restore_locked(bool recorded,
"entry); ignored", names[i]->d_name);
goto next;
}
+ if (set[cnt].type == UPATCH_TYPE_JAVA) {
+ ret = java_restore(set[cnt].name, path, recorded);
+ if (!ret)
+ cnt++;
+ goto next;
+ }
if (upatch_loaded_pins(set[cnt].name)) {
upatch_payload_sha256(set[cnt].name, pinned_hex,
sizeof(pinned_hex));
@@ -1136,6 +1177,19 @@ next:
return 0;
}
+/*
+ * A failure leaves JVMs without the agents, which the status of the
+ * archive shows, and does not stop the boot.
+ */
+static void java_restore_options(void)
+{
+ int ret = java_agents_sync();
+
+ if (ret)
+ pr_warn("boot-restore: cannot bring the Java agents and %s in line: %s",
+ JAVA_ENV_PATH, strerror(-ret));
+}
+
/*
* A run after the register was bound this boot runs beside the upatch
* commands the completed activation admits, so it takes their lock: an
@@ -1158,6 +1212,8 @@ static int boot_restore(bool recorded,
}
}
ret = boot_restore_locked(recorded, out_set, out_n);
+ if (!ret)
+ java_restore_options();
eventlog_unlock(lock);
return ret;
}
@@ -1522,6 +1578,10 @@ static int run_init(void)
ret = init_bpffs();
if (ret)
return init_phase_error(ret, "private bpffs setup");
+ /* Labelled before anyone else can make it, as RUN_DIR is. */
+ ret = java_agent_dir_prepare();
+ if (ret)
+ return init_phase_error(ret, "Java agent directory setup");
ret = init_keyring();
if (ret)
diff --git a/builtin-keys.c b/builtin-keys.c
index 0edd8bfa..7c88358b 100644
--- a/builtin-keys.c
+++ b/builtin-keys.c
@@ -582,12 +582,12 @@ static int check_cert_algorithm(const __u8 *der, size_t der_sz,
static int check_voucher_live(const struct trusted_set *set,
const __u8 voucher[32])
{
+ const struct trusted_cert *member;
struct identity id;
const __u8 *der = NULL;
key_serial_t ring;
size_t der_sz = 0;
int ret = 0;
- size_t i;
if (identity_read(&id) ||
id.keyring_type != SIG_KEYRING_BPF)
@@ -595,13 +595,10 @@ static int check_voucher_live(const struct trusted_set *set,
ring = keyring_bpf_serial();
if (ring <= 0)
return 0;
- for (i = 0; i < set->n; i++) {
- if (memcmp(set->certs[i].fingerprint, voucher, 32) == 0)
- break;
- }
- if (i == set->n)
+ member = keys_member(set, voucher);
+ if (!member)
return -ENOKEY;
- ret = keys_cert_der(&set->certs[i], &der, &der_sz);
+ ret = keys_cert_der(member, &der, &der_sz);
if (ret)
return ret;
ret = keyring_holds_cert(ring, der, der_sz);
diff --git a/builtin-status.c b/builtin-status.c
index 1970a52f..05aaef93 100644
--- a/builtin-status.c
+++ b/builtin-status.c
@@ -39,6 +39,7 @@
#include "util/help.h"
#include "util/io.h"
+#include "util/java_agent.h"
#include "util/json.h"
#include "util/identity.h"
#include "util/keepalive.h"
@@ -400,55 +401,33 @@ static const struct help status_help = {
.n_sections = ARRAY_SIZE(status_help_sections),
};
-static size_t build_upatches_table(struct dirent **ups, int n_ups,
- struct upatch_table_row **out)
-{
- struct upatch_table_row *rows;
- struct btf *vbtf;
- int i;
-
- if (n_ups <= 0) {
- *out = NULL;
- return 0;
- }
- rows = xcalloc((size_t)n_ups, sizeof(*rows));
- if (!rows) {
- *out = NULL;
- return 0;
- }
- /*
- * vmlinux BTF loaded once; per-upatch reload would burn syscalls
- * for no gain since every shirudo upatch attaches to vmlinux.
- */
- vbtf = btf__load_vmlinux_btf();
- for (i = 0; i < n_ups; i++) {
- struct upatch_table_row *r = &rows[i];
- struct map_summary *list = NULL;
- char raw_name[UPATCH_NAME_MAX + 1];
- size_t nm = 0;
- const char *name = ups[i]->d_name;
+struct java_rows {
+ struct upatch_table_row *rows;
+ size_t n;
+};
- if (upatch_name_from_bpffs(raw_name, sizeof(raw_name),
- ups[i]->d_name) == 0)
- name = raw_name;
+/* A Java agent has no pin: its jar's change time is when it was loaded. */
+static int java_row(const char *name,
+ const __u8 payload[UPATCH_PAYLOAD_HASH_LEN], void *ctx)
+{
+ struct java_rows *j = ctx;
+ struct upatch_table_row *r;
+ char path[PATH_MAX];
+ struct stat st;
- strscpy(r->name, name, sizeof(r->name));
- upatch_resolve_location(vbtf, name,
- r->location,
- sizeof(r->location));
- upatch_loaded_at(name, r->loaded_at,
- sizeof(r->loaded_at));
- upatch_payload_sha256(name,
- r->payload_sha256,
- sizeof(r->payload_sha256));
- upatch_maps_list_one(name, &list, &nm);
- r->n_maps = (__u32)nm;
- map_summary_free(list, nm);
- r->age_sec = upatch_age_sec(r->loaded_at);
- }
- btf__free(vbtf);
- *out = rows;
- return (size_t)n_ups;
+ r = xreallocarray(j->rows, j->n, j->n + 1, sizeof(*r));
+ if (!r)
+ return -ENOMEM;
+ j->rows = r;
+ r = &j->rows[j->n++];
+ memset(r, 0, sizeof(*r));
+ strscpy(r->name, name, sizeof(r->name));
+ strscpy(r->location, "java", sizeof(r->location));
+ hex_encode(payload, UPATCH_PAYLOAD_HASH_LEN, r->payload_sha256);
+ if (!java_agent_path(name, path, sizeof(path)) && !stat(path, &st))
+ iso8601(st.st_ctim.tv_sec, r->loaded_at, sizeof(r->loaded_at));
+ r->age_sec = upatch_age_sec(r->loaded_at);
+ return 0;
}
static const char *roles_str(int is_target, int is_operator)
@@ -555,47 +534,100 @@ static bool keepalive_upatch_not_ok(const char *name)
return access(path, F_OK) == 0;
}
-/* The set_digest of an init event, over every upatch pinned now. */
-static int keepalive_loaded_set(struct keepalive_view *v)
+struct loaded_set {
+ struct measured_upatch *set;
+ size_t n;
+ size_t cap;
+ __u64 not_ok;
+};
+
+static struct measured_upatch *loaded_set_next(struct loaded_set *l)
+{
+ size_t cap = l->cap ? 2 * l->cap : 16;
+ struct measured_upatch *set;
+
+ if (l->n == l->cap) {
+ set = xreallocarray(l->set, l->cap, cap, sizeof(*set));
+ if (!set)
+ return NULL;
+ l->set = set;
+ l->cap = cap;
+ }
+ return &l->set[l->n];
+}
+
+static void loaded_set_take(struct loaded_set *l)
+{
+ if (keepalive_upatch_not_ok(l->set[l->n].name))
+ l->not_ok++;
+ l->n++;
+}
+
+static int loaded_set_pins(struct loaded_set *l)
{
- __u8 none[CHAIN_DIGEST_LEN] = {}, digest[CHAIN_DIGEST_LEN];
- struct measured_upatch *set = NULL;
- __u8 event[CHAIN_DIGEST_LEN];
struct dirent **ups = NULL;
int n, i, ret = 0;
- size_t m = 0;
n = scandir(BPFFS_UPATCHES_DIR, &ups, notdot, alphasort);
- if (n < 0)
- n = 0;
- if (n) {
- set = xcalloc((size_t)n, sizeof(*set));
- if (!set)
+ for (i = 0; i < n; i++) {
+ struct measured_upatch *u = ret ? NULL : loaded_set_next(l);
+
+ if (!u) {
ret = -ENOMEM;
+ } else if (!upatch_name_from_bpffs(u->name, sizeof(u->name),
+ ups[i]->d_name)) {
+ upatch_payload_sha256(u->name, u->payload_hex,
+ sizeof(u->payload_hex));
+ loaded_set_take(l);
+ }
+ libc_free(ups[i]);
}
- v->not_ok = 0;
- for (i = 0; !ret && i < n; i++) {
- struct measured_upatch *u = &set[m];
+ libc_free(ups);
+ return ret;
+}
- if (upatch_name_from_bpffs(u->name, sizeof(u->name),
- ups[i]->d_name))
- continue;
- upatch_payload_sha256(u->name, u->payload_hex,
- sizeof(u->payload_hex));
- if (keepalive_upatch_not_ok(u->name))
- v->not_ok++;
- m++;
- }
+/*
+ * The member carries no type: the tree operation a collector compares the
+ * set with names an upatch and its payload, not what kind it is.
+ */
+static int loaded_set_java(const char *name,
+ const __u8 payload[UPATCH_PAYLOAD_HASH_LEN],
+ void *ctx)
+{
+ struct loaded_set *l = ctx;
+ struct measured_upatch *u = loaded_set_next(l);
+
+ if (!u)
+ return -ENOMEM;
+ strscpy(u->name, name, sizeof(u->name));
+ hex_encode(payload, UPATCH_PAYLOAD_HASH_LEN, u->payload_hex);
+ loaded_set_take(l);
+ return 0;
+}
+
+/*
+ * The set_digest form of an init event, over every upatch loaded now:
+ * the pinned ones and the Java agents installed as archived.
+ */
+static int keepalive_loaded_set(struct keepalive_view *v)
+{
+ __u8 none[CHAIN_DIGEST_LEN] = {}, digest[CHAIN_DIGEST_LEN];
+ __u8 event[CHAIN_DIGEST_LEN];
+ struct loaded_set l = {};
+ int ret;
+
+ v->not_ok = 0;
+ ret = loaded_set_pins(&l);
+ if (!ret)
+ ret = java_agents_each_loaded(loaded_set_java, &l);
if (!ret)
- ret = chain_init_event(none, set, m, none, digest, event);
+ ret = chain_init_event(none, l.set, l.n, none, digest, event);
if (!ret) {
hex_encode(digest, sizeof(digest), v->set_sha256);
- v->count = m;
+ v->count = l.n;
+ v->not_ok = l.not_ok;
}
- for (i = 0; i < n; i++)
- libc_free(ups[i]);
- libc_free(ups);
- xfree(set, (size_t)n * sizeof(*set));
+ xfree(l.set, l.cap * sizeof(*l.set));
return ret;
}
@@ -1163,6 +1195,7 @@ struct status_view {
struct status_keyring dmv;
struct dirent **ups;
int n_ups;
+ struct java_rows java;
struct status_pins pins;
struct asset_view assets;
struct guard_counts counts;
@@ -1304,6 +1337,11 @@ static int count_unmeasured(const struct measured_set *mset, char *names)
unmeasured = archived < 0 ? archived :
unmeasured + archived;
}
+ if (unmeasured >= 0) {
+ int jars = java_agents_unbacked(note_unmeasured, names);
+
+ unmeasured = jars < 0 ? jars : unmeasured + jars;
+ }
return unmeasured;
}
@@ -1327,8 +1365,8 @@ static void status_check_pins(struct status_pins *pins)
pins->unmeasured_names);
upatch_checks_run(mset, &checks);
pins->xdp_tampered = checks.nr_changed;
- pins->links_lost = measured_unpinned(mset, note_unmeasured,
- pins->links_lost_names);
+ pins->links_lost = upatch_unpinned(mset, note_unmeasured,
+ pins->links_lost_names);
pins->links_lost = pins->links_lost < 0 ? pins->links_lost :
pins->links_lost + checks.nr_lost;
pins->xdp_uncovered = checks.nr_uncovered;
@@ -1452,6 +1490,8 @@ static void status_gather(struct status_view *v, bool include_system)
v->n_ups = scandir(BPFFS_UPATCHES_DIR, &v->ups, notdot, alphasort);
if (v->n_ups < 0)
v->n_ups = 0;
+ if (java_agents_each_loaded(java_row, &v->java))
+ pr_warn("status: the Java agents could not all be read");
status_check_pins(&v->pins);
gather_assets(&v->assets);
v->counts.tamper_rc = tamper_read(&v->counts.tamper);
@@ -1470,6 +1510,7 @@ static void status_view_free(struct status_view *v)
for (i = 0; i < v->n_ups; i++)
libc_free(v->ups[i]);
libc_free(v->ups);
+ xfree(v->java.rows, v->java.n * sizeof(*v->java.rows));
}
static void emit_verdict_json(struct json_emit *e,
@@ -1543,11 +1584,66 @@ static void emit_certs_json(struct json_emit *e, const struct status_view *v)
json_kv_null(e, "certs_enrolled");
}
-static void emit_upatches_json(struct json_emit *e, struct dirent **ups,
- int n_ups)
+/* The rows of the pinned upatches, then those of the Java agents. */
+static size_t build_upatches_table(const struct status_view *v,
+ struct upatch_table_row **out)
+{
+ size_t n_rows = (size_t)v->n_ups + v->java.n;
+ struct dirent **ups = v->ups;
+ struct upatch_table_row *rows;
+ int n_ups = v->n_ups;
+ struct btf *vbtf;
+ int i;
+
+ *out = NULL;
+ if (!n_rows)
+ return 0;
+ rows = xcalloc(n_rows, sizeof(*rows));
+ if (!rows)
+ return 0;
+ if (v->java.n)
+ memcpy(&rows[n_ups], v->java.rows,
+ v->java.n * sizeof(*rows));
+ /*
+ * vmlinux BTF loaded once; per-upatch reload would burn syscalls
+ * for no gain since every shirudo upatch attaches to vmlinux.
+ */
+ vbtf = btf__load_vmlinux_btf();
+ for (i = 0; i < n_ups; i++) {
+ struct upatch_table_row *r = &rows[i];
+ struct map_summary *list = NULL;
+ char raw_name[UPATCH_NAME_MAX + 1];
+ size_t nm = 0;
+ const char *name = ups[i]->d_name;
+
+ if (upatch_name_from_bpffs(raw_name, sizeof(raw_name),
+ ups[i]->d_name) == 0)
+ name = raw_name;
+
+ strscpy(r->name, name, sizeof(r->name));
+ upatch_resolve_location(vbtf, name,
+ r->location,
+ sizeof(r->location));
+ upatch_loaded_at(name, r->loaded_at,
+ sizeof(r->loaded_at));
+ upatch_payload_sha256(name,
+ r->payload_sha256,
+ sizeof(r->payload_sha256));
+ upatch_maps_list_one(name, &list, &nm);
+ r->n_maps = (__u32)nm;
+ map_summary_free(list, nm);
+ r->age_sec = upatch_age_sec(r->loaded_at);
+ }
+ btf__free(vbtf);
+ *out = rows;
+ return n_rows;
+}
+
+static void emit_upatches_json(struct json_emit *e,
+ const struct status_view *v)
{
struct upatch_table_row *rows = NULL;
- size_t n_rows = build_upatches_table(ups, n_ups, &rows);
+ size_t n_rows = build_upatches_table(v, &rows);
upatch_table_emit_json(e, rows, n_rows);
xfree(rows, n_rows * sizeof(*rows));
@@ -1686,7 +1782,7 @@ static void status_emit_json(struct json_emit *e, const struct status_view *v,
keyring_emit_json(e, "bpf_keyring", &v->bpf, "primary");
keyring_emit_json(e, "dm_verity_keyring", &v->dmv, "config");
json_kv_bool(e, "signing_key_present", v->is_operator);
- emit_upatches_json(e, v->ups, v->n_ups);
+ emit_upatches_json(e, v);
emit_assets_json(e, &v->assets);
emit_guard_counts_json(e, &v->counts);
emit_config_json(e, v->config_state, v->config_root_hex);
@@ -1708,7 +1804,7 @@ static size_t status_json_cap(const struct status_view *v,
{
size_t json_cap;
- json_cap = 16384 + (size_t)v->n_ups *
+ json_cap = 16384 + ((size_t)v->n_ups + v->java.n) *
(6 * sizeof(struct upatch_table_row) + 256);
json_cap += (v->bpf.n_certs + v->bpf.n_links + v->dmv.n_certs +
v->dmv.n_links) *
@@ -1919,7 +2015,7 @@ static void status_print_text(const struct status_view *v,
verdict = status_verdict(&v->cin);
status_reason(&v->cin, reason, sizeof(reason));
nc = conditions(&v->cin, conds, ARRAY_SIZE(conds));
- n_rows = build_upatches_table(v->ups, v->n_ups, &rows);
+ n_rows = build_upatches_table(v, &rows);
/*
* A section a condition vouches for says nothing the
* condition did not: it unfolds when that condition is not
diff --git a/builtin-upatch.c b/builtin-upatch.c
index fee93c82..5af8918b 100644
--- a/builtin-upatch.c
+++ b/builtin-upatch.c
@@ -45,6 +45,7 @@
#include "util/elf_target.h"
#include "util/help.h"
#include "util/io.h"
+#include "util/java_agent.h"
#include "util/json.h"
#include "util/kernel_abi.h"
#include "util/identity.h"
@@ -749,7 +750,8 @@ static int cmd_upatch_list(int argc, const char **argv)
hex_encode(u.hdr.payload_sha256, 32, payload_hex);
type = upatch_is_unload(&u) ? "unload" : "load";
payload_type = upatch_type_str(&u);
- loaded = upatch_is_loaded(name);
+ loaded = u.hdr.type == UPATCH_TYPE_JAVA ?
+ java_agent_loaded(name) : upatch_is_loaded(name);
upatch_close(&u);
if (json) {
@@ -2171,18 +2173,6 @@ static int refuse_unload_directive(const struct signed_load *sl)
return 0;
}
-/* Only a BPF payload has a loader for the kernel to verify and run. */
-static int refuse_foreign_payload(const struct signed_load *sl)
-{
- if (sl->u->hdr.type == UPATCH_TYPE_BPF)
- return 0;
- pr_err("upatch load: %s carries a %s payload, not BPF", sl->label,
- upatch_type_str(sl->u));
- rep_fail(sl->rep, "parse", "parser_rejected", 0,
- "not a BPF payload");
- return 1;
-}
-
/*
* The pin directory, the archive and unload share the raw name. Boot
* restore reaches here without the command-level check, so validate it
@@ -2557,7 +2547,7 @@ static int signed_load_run(struct signed_load *sl)
const struct upatch *u = sl->u;
int ret;
- if (refuse_unload_directive(sl) || refuse_foreign_payload(sl) ||
+ if (refuse_unload_directive(sl) ||
trust_anchor_keyring(&sl->keyring, &sl->serial, sl->rep) ||
upatch_signed_name_check(sl) || upatch_payload_check(sl) ||
upatch_attach_prepare(sl) || loader_map_prepare(sl) ||
@@ -2603,12 +2593,75 @@ static void signed_load_release(struct signed_load *sl)
close(sl->map_fd);
}
+static int java_verify(const struct upatch *u, const char *label,
+ struct op_report *rep)
+{
+ int ret = java_upatch_verify(u);
+
+ if (!ret)
+ return 0;
+ pr_err("upatch: %s: the Java upatch %s (%s)", label,
+ ret == -EKEYREJECTED ? "is not signed by an enrolled key" :
+ ret == -EBADMSG ? "is malformed or its payload digest differs" :
+ "cannot be verified", strerror(-ret));
+ rep_fail(rep, "java_verify",
+ ret == -EKEYREJECTED ? "signature_rejected" :
+ ret == -EBADMSG ? "parser_rejected" : "unknown", -ret,
+ "Java upatch verification failed");
+ return 1;
+}
+
+/*
+ * A Java upatch has no loader for the kernel to verify: its signature
+ * is checked here, against the keys the .bpf keyring holds, and a load
+ * installs its jar, sealed, from the bytes checked.
+ */
+static int java_apply(const struct upatch *u, const char *label,
+ bool verify_only, struct op_report *rep)
+{
+ char name[UPATCH_NAME_MAX + 1];
+ const void *jar;
+ __u32 len;
+ int ret;
+
+ if (!verify_only && upatch_is_unload(u)) {
+ pr_err("upatch load: %s is an UNLOAD directive; "
+ "use `shirudo upatch unload`", label);
+ rep_fail(rep, "parse", "parser_rejected", 0,
+ "is an UNLOAD directive");
+ return 1;
+ }
+ upatch_header_name(u, name);
+ if (!upatch_name_valid(name)) {
+ pr_err("upatch: %s: refusing unsafe upatch name '%s'", label,
+ name);
+ rep_fail(rep, "parse", "parser_rejected", 0,
+ "unsafe upatch name");
+ return 1;
+ }
+ if (java_verify(u, label, rep))
+ return 1;
+ if (verify_only)
+ return 0;
+ jar = upatch_signed_jar(u, &len);
+ ret = java_agent_install(name, jar, len);
+ if (ret) {
+ pr_err("upatch load: cannot install the jar of %s: %s", name,
+ strerror(-ret));
+ rep_fail(rep, "java_install", "unknown", -ret,
+ "cannot install the jar");
+ return 1;
+ }
+ pr_audit("upatch load: %s installed, Java agent %u bytes", name, len);
+ return 0;
+}
+
/* Shared by `upatch load` and boot restore: one signature-verified path. */
/*
* Load and run the signed loader of u, which the caller read once and
* closes: the name the signature covers, the loader the kernel verifies
* and what the caller then measures and archives are all those bytes.
- * label names them in messages.
+ * label names them in messages. A Java upatch takes java_apply().
*/
static int upatch_apply(struct upatch *u, const char *label, bool verify_only,
struct op_report *rep)
@@ -2627,6 +2680,8 @@ static int upatch_apply(struct upatch *u, const char *label, bool verify_only,
};
int ret;
+ if (u->hdr.type == UPATCH_TYPE_JAVA)
+ return java_apply(u, label, verify_only, rep);
sl.vlog = xmalloc(VERIFIER_LOG_MAX);
if (!sl.vlog) {
rep_fail(rep, "parse", "unknown", ENOMEM, "out of memory");
@@ -2820,12 +2875,13 @@ static int append_upatch_event(const char *type, const char *name,
* unmeasured success: init guarantees the register exists. *measured
* tells a failure after the register moved from one before it.
*/
-static int upatch_chain_event_locked(const char *tag, const char *type,
+static int upatch_chain_event_locked(__u32 payload_type, bool load,
const char *op, const char *name,
const __u8 payload[32],
const char *reason, char out_chain[65],
bool *measured)
{
+ const char *type = eventlog_upatch_record(payload_type, load);
__u8 event[32], chain[32];
char chain_hex[65];
int ret;
@@ -2834,7 +2890,8 @@ static int upatch_chain_event_locked(const char *tag, const char *type,
out_chain[0] = '\0';
if (measured)
*measured = false;
- ret = chain_upatch_event(tag, name, payload, event);
+ ret = chain_upatch_event(chain_upatch_tag(payload_type, load), name,
+ payload, event);
if (ret) {
pr_err("upatch %s: cannot hash the event (category: tpm_error)",
op);
@@ -3134,13 +3191,32 @@ static int read_upatch(const char *src, __u8 **buf, size_t *len,
return ret;
}
-/* Take a load the register did not record back out: pins, then archive. */
-static int undo_load(const char *name)
+/*
+ * A failure here leaves the jars or the options a JVM started next reads
+ * out of step with the agents loaded, which the next upatch command and
+ * init bring back in line. It refuses nothing: a jar it keeps by mistake
+ * belongs to no archive, and one it cannot account for it keeps.
+ */
+static void java_options_sync(const char *op)
+{
+ int ret = java_agents_sync();
+
+ if (ret)
+ pr_warn("upatch %s: cannot update %s: %s; JVMs started now do not see the change",
+ op, JAVA_ENV_PATH, strerror(-ret));
+}
+
+/*
+ * Take a load the register did not record back out: pins or jar, then
+ * archive. A Java upatch has no pins and a BPF one no jar.
+ */
+static int undo_load(const char *name, __u32 type)
{
char persisted[PATH_MAX];
int ret;
- ret = remove_pin_dir(name);
+ ret = type == UPATCH_TYPE_JAVA ? java_agent_retire(name) :
+ remove_pin_dir(name);
if (!ret && strsprintf(persisted, sizeof(persisted), "%s/%s.upatch",
UPATCHES_DIR, name) >= 0 &&
unlink(persisted) != 0 && errno != ENOENT)
@@ -3148,9 +3224,9 @@ static int undo_load(const char *name)
return ret;
}
-static void unload_unmeasured(const char *name)
+static void unload_unmeasured(const char *name, __u32 type)
{
- int ret = undo_load(name);
+ int ret = undo_load(name, type);
if (ret)
pr_err("upatch load: %s is loaded but not measured and could "
@@ -3164,7 +3240,7 @@ static void unload_unmeasured(const char *name)
/* The rest are still undone when one fails; *ctx keeps the first error. */
static int undo_unmeasured_pin(const char *name, void *ctx)
{
- int *failed = ctx, ret = undo_load(name);
+ int *failed = ctx, ret = undo_load(name, UPATCH_TYPE_BPF);
if (ret) {
pr_err("upatch: %s is pinned without a record of this boot and could not be undone: %s; operator must reconcile",
@@ -3236,9 +3312,12 @@ static int undo_unmeasured(struct op_report *rep, const char *op)
ret = measured_unmeasured_archives(set, undo_unmeasured_archive,
&failed);
measured_set_free(set);
- if (ret >= 0 && !failed)
+ if (ret >= 0)
+ ret = failed;
+ if (!ret) {
+ java_options_sync(op);
return 0;
- ret = ret < 0 ? ret : failed;
+ }
pr_err("upatch %s: cannot undo what this boot's records do not cover: %s; refused",
op, strerror(-ret));
rep_fail(rep, "tpm_extend", "tpm_error", ret,
@@ -3323,22 +3402,30 @@ static int upatch_load(const struct load_args *args)
* it. An install of the very payload loaded is done: bpm retries one
* that a stop cut off between this load and its own record.
*/
- if (!upatch_pin_payload(name, live)) {
- if (args->loaded_is_done &&
- !memcmp(live, payload, sizeof(live))) {
- pr_info("upatch load: %s is already loaded with this payload",
- name);
- rep.ok = true;
- rep.category = "already_loaded";
- ret = 0;
- goto done;
- }
- pr_err("upatch load: %s is already loaded; unload it with its signed directive first",
- name);
+ err = upatch_loaded_payload(name, live);
+ if (!err && args->loaded_is_done &&
+ !memcmp(live, payload, sizeof(live))) {
+ pr_info("upatch load: %s is already loaded with this payload",
+ name);
+ rep.ok = true;
+ rep.category = "already_loaded";
+ ret = 0;
+ goto done;
+ }
+ if (!err || err == -ESTALE) {
+ pr_err("upatch load: %s is already loaded%s; unload it with its signed directive first",
+ name, err ? ", without the jar it archived" : "");
rep_fail(&rep, "pin", "already_loaded", EEXIST,
"upatch already loaded");
goto done;
}
+ if (err != -ENOENT) {
+ pr_err("upatch load: cannot tell whether %s is loaded: %s; nothing loaded",
+ name, strerror(-err));
+ rep_fail(&rep, "pin", "unknown", -err,
+ "cannot tell whether the upatch is loaded");
+ goto done;
+ }
if (upatch_apply(&u, file, false, &rep) != 0)
goto done;
@@ -3357,24 +3444,26 @@ static int upatch_load(const struct load_args *args)
if (err) {
pr_err("upatch load: loaded but not archived under %s: %s; "
"not measured", UPATCHES_DIR, strerror(-err));
- unload_unmeasured(name);
+ unload_unmeasured(name, u.hdr.type);
rep_fail(&rep, "persist", "unknown", -err,
"persist failed; the load was undone");
goto done;
}
- err = upatch_chain_event_locked("shirudo-upatch", "upatch_load",
- "load", name, payload, NULL,
- rep.chain_after, &measured);
+ err = upatch_chain_event_locked(u.hdr.type, true, "load", name,
+ payload, NULL, rep.chain_after,
+ &measured);
if (err) {
if (!measured)
- unload_unmeasured(name);
+ unload_unmeasured(name, u.hdr.type);
rep_fail(&rep, "tpm_extend", chain_event_category(err, measured),
err, measured ?
"eventlog append failed after the extend" :
"chain extend failed; the load was undone");
goto done;
}
+ if (u.hdr.type == UPATCH_TYPE_JAVA)
+ java_options_sync("load");
rep.ok = true;
rep.phase = "done";
rep.tpm_present = rep.chain_after[0] != '\0';
@@ -3406,6 +3495,69 @@ static int cmd_upatch_load(int argc, const char **argv)
return upatch_load(&args);
}
+/*
+ * The unload of a Java upatch, under the register lock and past the
+ * directive's verification: the archive must be the Java load the
+ * directive names, then the event, then the jar and the archive go and
+ * the options follow. 0 on success, 1 refused or failed.
+ */
+static int java_unload_locked(const char *name,
+ const __u8 payload[UPATCH_PAYLOAD_HASH_LEN],
+ const char *persisted, struct op_report *rep)
+{
+ struct upatch archived;
+ __u32 type;
+ int err;
+
+ err = upatch_archive_verify(name, payload, &archived);
+ if (err == -ESTALE && access(persisted, F_OK)) {
+ pr_info("upatch unload: %s already unloaded (no archive)", name);
+ java_options_sync("unload");
+ rep->ok = true;
+ rep->category = "already_unloaded";
+ strscpy(rep->message, "already unloaded", sizeof(rep->message));
+ return 0;
+ }
+ if (!err) {
+ type = archived.hdr.type;
+ upatch_close(&archived);
+ if (type != UPATCH_TYPE_JAVA)
+ err = -ESTALE;
+ }
+ if (err) {
+ pr_err("upatch unload: payload_mismatch, %s is not the Java "
+ "upatch the directive expects; refused", persisted);
+ rep_fail(rep, "pin", "payload_mismatch",
+ err == -ESTALE ? EPERM : -err,
+ "archived payload does not match directive");
+ return 1;
+ }
+ err = upatch_chain_event_locked(UPATCH_TYPE_JAVA, false, "unload",
+ name, payload, NULL, rep->chain_after,
+ NULL);
+ if (err) {
+ rep_fail(rep, "tpm_extend", chain_event_category(err, false),
+ err, "chain extend failed; nothing removed");
+ return 1;
+ }
+ err = java_agent_retire(name);
+ if (!err && unlink(persisted) && errno != ENOENT)
+ err = -errno;
+ if (err) {
+ pr_err("upatch unload: measured, but failed to remove %s: %s; repeat the unload",
+ name, strerror(-err));
+ rep_fail(rep, "pin", "detach_failed", -err,
+ "removal failed after the event was measured");
+ return 1;
+ }
+ java_options_sync("unload");
+ pr_info("upatch unload: %s removed", name);
+ rep->ok = true;
+ rep->phase = "done";
+ rep->tpm_present = rep->chain_after[0] != '\0';
+ return 0;
+}
+
static int cmd_upatch_unload(int argc, const char **argv)
{
const char *file, *expect_chain, *expect_version_id, *report;
@@ -3505,6 +3657,10 @@ static int cmd_upatch_unload(int argc, const char **argv)
pr_err("upatch unload: signature verification failed; refusing");
goto done;
}
+ if (u.hdr.type == UPATCH_TYPE_JAVA) {
+ ret = java_unload_locked(name, payload, persisted, &rep);
+ goto done;
+ }
/*
* The live value is the xattr bpf2 guards; the expected one is
@@ -3556,7 +3712,12 @@ static int cmd_upatch_unload(int argc, const char **argv)
err = upatch_archive_verify(name, payload, &archived);
if (!err) {
+ /* Only its own signed directive unloads a Java upatch. */
+ if (archived.hdr.type != UPATCH_TYPE_BPF)
+ err = -ESTALE;
upatch_close(&archived);
+ }
+ if (!err) {
if (unlink(persisted) != 0 && errno != ENOENT)
pr_warn("upatch unload: could not remove %s: %s",
persisted, strerror(errno));
@@ -3586,9 +3747,8 @@ static int cmd_upatch_unload(int argc, const char **argv)
* fails after the event leaves a shield the register says is gone,
* which the next status reports and the operator can repeat.
*/
- err = upatch_chain_event_locked("shirudo-unload", "upatch_unload",
- "unload", name, payload, NULL,
- rep.chain_after, NULL);
+ err = upatch_chain_event_locked(UPATCH_TYPE_BPF, false, "unload", name,
+ payload, NULL, rep.chain_after, NULL);
if (err) {
rep_fail(&rep, "tpm_extend", chain_event_category(err, false),
err, "chain extend failed; nothing detached");
@@ -3631,6 +3791,24 @@ done:
return ret;
}
+/*
+ * 1 when name runs: its pins, or the jar of its Java archive installed as
+ * archived. A Java archive whose jar is missing or another is purged as an
+ * archive alone, as a BPF one without pins is.
+ */
+static int purge_is_loaded(const char *name, __u32 type)
+{
+ __u8 payload[UPATCH_PAYLOAD_HASH_LEN];
+ int ret;
+
+ if (type != UPATCH_TYPE_JAVA)
+ return upatch_pinned(name);
+ ret = java_agent_payload(name, payload);
+ if (ret == -ESTALE || ret == -ENOENT)
+ return 0;
+ return ret ? ret : 1;
+}
+
static int upatch_purge_locked(const char *name, const struct cert *signer,
const char *reason)
{
@@ -3638,6 +3816,7 @@ static int upatch_purge_locked(const char *name, const struct cert *signer,
char persisted[PATH_MAX];
int fd, loaded, ret;
struct upatch u;
+ __u32 type;
if (strsprintf(persisted, sizeof(persisted), "%s/%s.upatch",
UPATCHES_DIR, name) < 0)
@@ -3652,24 +3831,25 @@ static int upatch_purge_locked(const char *name, const struct cert *signer,
return ret;
ret = cms_signed_by(upatch_signature(&u), u.hdr.signature_len, signer);
memcpy(payload, u.hdr.payload_sha256, sizeof(payload));
+ type = u.hdr.type;
upatch_close(&u);
if (ret != 1)
return ret < 0 ? ret : -ESTALE;
/* As for unload: the event first, then the detach it describes. */
- loaded = upatch_pinned(name);
+ loaded = purge_is_loaded(name, type);
if (loaded < 0)
return loaded;
if (loaded) {
- ret = upatch_chain_event_locked("shirudo-unload",
- "upatch_unload", "purge", name,
+ ret = upatch_chain_event_locked(type, false, "purge", name,
payload, reason, NULL, NULL);
if (ret)
return ret;
- ret = remove_pin_dir(name);
+ ret = type == UPATCH_TYPE_JAVA ? java_agent_retire(name) :
+ remove_pin_dir(name);
if (ret) {
pr_err("upatch purge: measured, but failed to remove "
- "the pin for %s: %s", name, strerror(-ret));
+ "%s: %s", name, strerror(-ret));
return ret;
}
}
@@ -3678,6 +3858,8 @@ static int upatch_purge_locked(const char *name, const struct cert *signer,
strerror(errno));
return -errno;
}
+ if (type == UPATCH_TYPE_JAVA)
+ java_options_sync("purge");
pr_audit("upatch purge: name=%s reason=%s %s", name, reason,
loaded ? "detached" : "archive_only");
return loaded ? 1 : 0;
diff --git a/testing/functional/upatch/t3114-java-agent.sh b/testing/functional/upatch/t3114-java-agent.sh
new file mode 100755
index 00000000..1480492d
--- /dev/null
+++ b/testing/functional/upatch/t3114-java-agent.sh
@@ -0,0 +1,158 @@
+#!/bin/sh
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+#
+# t3114 -- a Java agent upatch: its load installs the jar sealed and
+# readable by any user, names it in JAVA_TOOL_OPTIONS and measures a
+# java_load; one signed by another key, or relabelled BPF, is refused, as
+# a BPF unload directive naming it is; its unload measures a java_unload,
+# takes the options out and leaves a jar that is an agent doing nothing.
+
+cd "$(dirname "$0")/../.."
+. ./integration-lib.sh
+target_guard
+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"
+
+FIXTURES=${SHIRUDO_TEST_FIXTURES_DIR:?target fixture directory is not set}
+NAME=shirudo-test-java
+LOAD="$FIXTURES/$NAME.upatch"
+UNLOAD="$FIXTURES/$NAME.unload.upatch"
+BPF_UNLOAD="$FIXTURES/$NAME.bpf-unload.upatch"
+FOREIGN="$FIXTURES/$NAME-foreign.upatch"
+JAR=/run/shirudo-java/$NAME.jar
+ENV_FILE=/run/environment.d/shirudo.conf
+EVENTLOG=/var/lib/shirudo/eventlog
+WORK=$(mktemp -d)
+
+for f in "$LOAD" "$UNLOAD" "$BPF_UNLOAD" "$FOREIGN" "$FIXTURES/$NAME.jar"; do
+ [ -s "$f" ] || test_skip_all "missing fixture $f"
+done
+
+restore() {
+ "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck \
+ >/dev/null 2>&1 || true
+ rm -rf "$WORK"
+}
+trap restore EXIT HUP INT TERM
+
+last_event() {
+ tail -n 1 "$EVENTLOG" | python3 -c '
+import json, sys
+r = json.loads(sys.stdin.read())
+print(r["type"], r.get("upatch", {}).get("name", ""))'
+}
+
+load_report() {
+ "$SHIRUDO_BIN" upatch load "$1" --no-precheck --report=- 2>/dev/null |
+ report_field category
+}
+
+test_expect_success 'load installs the jar sealed and measures a java_load' '
+ ( umask 077 &&
+ "$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck >/dev/null 2>&1 ) &&
+ cmp "$JAR" "$FIXTURES/$NAME.jar" &&
+ [ "$(stat -c %a "$JAR")" = 644 ] &&
+ [ "$(last_event)" = "java_load $NAME" ] &&
+ "$SHIRUDO_BIN" upatch list --json | python3 -c "
+import json, sys
+u = [x for x in json.load(sys.stdin)[\"upatches\"] if x[\"name\"] == \"$NAME\"]
+assert u and u[0][\"loaded\"] and u[0][\"payload_type\"] == \"java\", u
+"
+'
+
+test_expect_success 'JAVA_TOOL_OPTIONS names the agent' '
+ grep -qxF "JAVA_TOOL_OPTIONS=\"\${JAVA_TOOL_OPTIONS:+\$JAVA_TOOL_OPTIONS }-javaagent:$JAR\"" "$ENV_FILE" &&
+ [ "$(stat -c %a "$ENV_FILE")" = 644 ] &&
+ [ "$(stat -c %a /run/environment.d)" = 755 ]
+'
+
+test_expect_success 'a user without privileges reads the jar' '
+ setpriv --reuid=65534 --regid=65534 --clear-groups \
+ cat "$JAR" >"$WORK/read.jar" &&
+ cmp "$WORK/read.jar" "$JAR"
+'
+
+test_expect_success 'root cannot change or remove the sealed jar' '
+ ! sh -c "printf x >>\"$JAR\"" 2>/dev/null &&
+ ! rm -f "$JAR" 2>/dev/null &&
+ cmp "$JAR" "$FIXTURES/$NAME.jar"
+'
+
+test_expect_success 'root cannot move the jar directory; the state root stays closed' '
+ [ "$(stat -c %a /run/shirudo-java)" = 755 ] &&
+ ! mv /run/shirudo-java /run/shirudo-java.moved 2>/dev/null &&
+ [ -d /run/shirudo-java ] &&
+ [ "$(stat -c %a /var/lib/shirudo)" = 700 ]
+'
+
+test_expect_success 'status counts the loaded agent as measured and in place' '
+ "$SHIRUDO_BIN" status --json >"$WORK/status.json" 2>/dev/null
+ python3 - "$WORK/status.json" <<-PY
+ import json, sys
+ d = json.load(open(sys.argv[1], encoding="utf-8"))
+ c = [c for c in d["conditions"] if c["type"] == "UpatchesMeasured"]
+ assert c and c[0]["status"] == "OK", c
+ u = [u for u in d["upatches_loaded"] if u["name"] == "$NAME"]
+ assert u and u[0]["location"] == "java" and u[0]["n_maps"] == 0, u
+ PY
+'
+
+test_expect_success 'a second load is refused as already_loaded' '
+ [ "$(load_report "$LOAD")" = already_loaded ]
+'
+
+test_expect_success 'a Java upatch another key signed is refused' '
+ [ "$(load_report "$FOREIGN")" = signature_rejected ] &&
+ [ ! -e /run/shirudo-java/$NAME-foreign.jar ] &&
+ [ ! -e /var/lib/shirudo/upatches/$NAME-foreign.upatch ]
+'
+
+# A loader of one instruction over the signature's first bytes passes the
+# bounds of a BPF header, so that only the signed type refuses the file.
+test_expect_success 'a Java upatch relabelled BPF does not open' '
+ python3 -c "
+import struct, sys
+b = bytearray(open(sys.argv[1], \"rb\").read())
+struct.pack_into(\"<II\", b, 304, 360, 8)
+struct.pack_into(\"<I\", b, 352, 1)
+open(sys.argv[2], \"wb\").write(b)
+" "$LOAD" "$WORK/relabelled.upatch" &&
+ [ "$(load_report "$WORK/relabelled.upatch")" = parser_rejected ]
+'
+
+test_expect_success 'a BPF unload directive that names the agent is refused' '
+ [ "$("$SHIRUDO_BIN" upatch unload "$BPF_UNLOAD" --no-precheck \
+ --report=- 2>/dev/null | report_field category)" = \
+ payload_mismatch ] &&
+ cmp "$JAR" "$FIXTURES/$NAME.jar" &&
+ [ -e /var/lib/shirudo/upatches/$NAME.upatch ] &&
+ [ "$(last_event)" = "java_load $NAME" ]
+'
+
+test_expect_success 'unload takes the agent and the options out and measures a java_unload' '
+ "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck \
+ >/dev/null 2>&1 &&
+ [ ! -e "$ENV_FILE" ] &&
+ [ ! -e /var/lib/shirudo/upatches/$NAME.upatch ] &&
+ [ "$(last_event)" = "java_unload $NAME" ]
+'
+
+# A user manager started before the unload still names the jar.
+test_expect_success 'the jar left behind is an agent that does nothing' '
+ [ "$(stat -c %a "$JAR")" = 644 ] &&
+ python3 -c "
+import sys, zipfile
+z = zipfile.ZipFile(sys.argv[1])
+assert z.namelist() == [\"META-INF/MANIFEST.MF\", \"shirudo/Unloaded.class\"]
+assert b\"Premain-Class: shirudo.Unloaded\" in z.read(\"META-INF/MANIFEST.MF\")
+" "$JAR" &&
+ if command -v java >/dev/null 2>&1; then
+ java "-javaagent:$JAR" -version >/dev/null 2>&1
+ fi &&
+ "$SHIRUDO_BIN" upatch list --json | python3 -c "
+import json, sys
+assert not [x for x in json.load(sys.stdin)[\"upatches\"] if x[\"name\"] == \"$NAME\"]
+"
+'
+
+test_done
diff --git a/testing/unit/java_agent.c b/testing/unit/java_agent.c
new file mode 100644
index 00000000..6a45d2d7
--- /dev/null
+++ b/testing/unit/java_agent.c
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include <errno.h>
+#include <string.h>
+
+#include "java_agent.h"
+#include "paths.h"
+#include "unit.h"
+
+static void agent_path_is_its_jar(void)
+{
+ char path[64];
+
+ ASSERT_EQ(java_agent_path("rasp", path, sizeof(path)), 0);
+ EXPECT_STREQ(path, JAVA_DIR "/rasp.jar");
+ EXPECT_EQ(java_agent_path("rasp", path, 8), -ENAMETOOLONG);
+}
+
+static void options_name_each_agent_in_order(void)
+{
+ static const char *const names[] = { "a", "b.c" };
+ char out[256];
+ int len;
+
+ len = java_tool_options(names, 2, out, sizeof(out));
+ EXPECT_STREQ(out, "JAVA_TOOL_OPTIONS=\"${JAVA_TOOL_OPTIONS:+$JAVA_TOOL_OPTIONS }"
+ "-javaagent:" JAVA_DIR
+ "/a.jar -javaagent:" JAVA_DIR "/b.c.jar\"\n");
+ EXPECT_EQ(len, (int)strlen(out));
+ len = java_tool_options(names, 1, out, sizeof(out));
+ EXPECT_STREQ(out, "JAVA_TOOL_OPTIONS=\"${JAVA_TOOL_OPTIONS:+$JAVA_TOOL_OPTIONS }"
+ "-javaagent:" JAVA_DIR
+ "/a.jar\"\n");
+ EXPECT_EQ(len, (int)strlen(out));
+}
+
+/* A line cut short would hand every JVM a broken option. */
+static void options_that_do_not_fit_are_refused(void)
+{
+ static const char *const names[] = { "a", "b" };
+ char out[256];
+ int full;
+
+ full = java_tool_options(names, 2, out, sizeof(out));
+ ASSERT_TRUE(full > 0);
+ EXPECT_EQ(java_tool_options(names, 2, out, (size_t)full), -E2BIG);
+ EXPECT_EQ(java_tool_options(names, 2, out, 4), -E2BIG);
+}
+
+static void agent_without_archive_is_not_loaded(void)
+{
+ EXPECT_FALSE(java_agent_loaded("shirudo-unit-no-such-upatch"));
+}
+
+static const struct unit_case cases[] = {
+ UNIT_CASE(agent_path_is_its_jar),
+ UNIT_CASE(options_name_each_agent_in_order),
+ UNIT_CASE(options_that_do_not_fit_are_refused),
+ UNIT_CASE(agent_without_archive_is_not_loaded),
+ {}
+};
+
+UNIT_SUITE(java_agent, cases);
diff --git a/testing/unit/keys.c b/testing/unit/keys.c
new file mode 100644
index 00000000..87894541
--- /dev/null
+++ b/testing/unit/keys.c
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include <string.h>
+
+#include "keys.h"
+#include "unit.h"
+
+static struct trusted_set set;
+
+static void member_is_found_by_fingerprint(void)
+{
+ __u8 absent[32];
+
+ memset(&set, 0, sizeof(set));
+ set.n = 2;
+ memset(set.certs[0].fingerprint, 0x11, 32);
+ memset(set.certs[1].fingerprint, 0x22, 32);
+ memset(absent, 0x33, sizeof(absent));
+
+ EXPECT_TRUE(keys_member(&set, set.certs[1].fingerprint) ==
+ &set.certs[1]);
+ EXPECT_TRUE(!keys_member(&set, absent));
+}
+
+/* Entries past n are a stale tail, not members. */
+static void member_past_the_count_is_none(void)
+{
+ __u8 stale[32];
+
+ memset(&set, 0, sizeof(set));
+ set.n = 1;
+ memset(set.certs[1].fingerprint, 0x22, 32);
+ memset(stale, 0x22, sizeof(stale));
+
+ EXPECT_TRUE(!keys_member(&set, stale));
+}
+
+static const struct unit_case cases[] = {
+ UNIT_CASE(member_is_found_by_fingerprint),
+ UNIT_CASE(member_past_the_count_is_none),
+ {}
+};
+
+UNIT_SUITE(keys, cases);
diff --git a/testing/vm/build-bundle-payload.sh b/testing/vm/build-bundle-payload.sh
index 00a882d0..b9727d2c 100755
--- a/testing/vm/build-bundle-payload.sh
+++ b/testing/vm/build-bundle-payload.sh
@@ -616,6 +616,42 @@ PY
done
}
+# A Java agent jar, a load and an unload of it, a BPF unload directive
+# that names its payload, and a load of it that a key the target does not
+# enrol signed.
+build_java_fixture()
+{
+ local builder="$REPO_ROOT/tools/shirudo-build/shirudo-build"
+ local jar="$FIXTURE_WORK/shirudo-test-java.jar"
+ local out="$TMP_DIR/fixtures/shirudo-test-java"
+ local trusted="$FIXTURE_WORK/trusted"
+ local payload
+
+ python3 -I - "$jar" <<'PY'
+import sys
+import zipfile
+
+with zipfile.ZipFile(sys.argv[1], "w") as z:
+ z.writestr("META-INF/MANIFEST.MF",
+ "Manifest-Version: 1.0\nPremain-Class: shirudo.test.Agent\n\n")
+ z.writestr("shirudo/test/Agent.class", b"\xca\xfe\xba\xbe")
+PY
+ cp "$jar" "$out.jar"
+ "$builder" "$jar" -o "$out.upatch" --name shirudo-test-java \
+ --key "$trusted/signing_key.pem" --cert "$trusted/cert.der"
+ payload="$("$REPO_ROOT/shirudo" upatch info "$out.upatch" --json |
+ python3 -c 'import json,sys; print(json.load(sys.stdin)["payload_sha256"])')"
+ "$builder" --unload shirudo-test-java --java --payload-sha256 "$payload" \
+ -o "$out.unload.upatch" \
+ --key "$trusted/signing_key.pem" --cert "$trusted/cert.der"
+ "$builder" --unload shirudo-test-java --payload-sha256 "$payload" \
+ -o "$out.bpf-unload.upatch" \
+ --key "$trusted/signing_key.pem" --cert "$trusted/cert.der"
+ "$builder" "$jar" -o "$out-foreign.upatch" --name shirudo-test-java-foreign \
+ --key "$FIXTURE_WORK/foreign/signing_key.pem" \
+ --cert "$FIXTURE_WORK/foreign/cert.der"
+}
+
build_obs_fixture()
{
local keys_dir="$1"
@@ -760,6 +796,7 @@ queue_fixture build_fixture basic.bpf.c shirudo-test-own-keyring "$FIXTURE_WORK/
queue_fixture build_policy_labels_fixture
queue_fixture build_policy_exec_graph_fixture
queue_fixture build_obs_fixture "$FIXTURE_WORK/trusted"
+queue_fixture build_java_fixture
wait_fixture_jobs
basic_payload="$($REPO_ROOT/shirudo upatch info \
diff --git a/util/io.c b/util/io.c
index 63bd2bee..bcd7fe34 100644
--- a/util/io.c
+++ b/util/io.c
@@ -212,7 +212,8 @@ int read_file(const char *path, size_t max, void *out, size_t *len)
if (fd < 0)
return fd;
} else {
- fd = open(path, O_RDONLY | O_CLOEXEC);
+ /* O_NONBLOCK: a FIFO is refused below, not waited on. */
+ fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
if (fd < 0)
return -errno;
}
diff --git a/util/java_agent.c b/util/java_agent.c
new file mode 100644
index 00000000..f38badbc
--- /dev/null
+++ b/util/java_agent.c
@@ -0,0 +1,499 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * The Java agents a target runs: the sealed jars of the loaded Java
+ * upatches and the JAVA_TOOL_OPTIONS file that names them.
+ */
+
+#include <dirent.h>
+#include <errno.h>
+#include <limits.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <shirudo/misc.h>
+#include <shirudo/string.h>
+
+#include "io.h"
+#include "java_agent.h"
+#include "malloc.h"
+#include "paths.h"
+#include "seal.h"
+#include "upatch.h"
+
+#define JAVA_OPTIONS_MAX (64u * 1024u)
+
+/*
+ * A jar a JVM takes as an agent that does nothing, left in place of an
+ * agent taken out: a user manager started before keeps naming the jar in
+ * JAVA_TOOL_OPTIONS, and a JVM given a missing jar, or one without a
+ * premain, does not start. It stores the manifest and the class of
+ *
+ * package shirudo;
+ *
+ * public final class Unloaded {
+ * public static void premain(String args) { }
+ * }
+ *
+ * built for Java 8 without debug information.
+ */
+static const __u8 java_placeholder[] = {
+ 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x21, 0x00, 0x6d, 0x6f, 0x09, 0xd7, 0x3a, 0x00, 0x00, 0x00, 0x3a, 0x00,
+ 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x4d, 0x45, 0x54, 0x41, 0x2d, 0x49,
+ 0x4e, 0x46, 0x2f, 0x4d, 0x41, 0x4e, 0x49, 0x46, 0x45, 0x53, 0x54, 0x2e,
+ 0x4d, 0x46, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x2d, 0x56,
+ 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x31, 0x2e, 0x30, 0x0d,
+ 0x0a, 0x50, 0x72, 0x65, 0x6d, 0x61, 0x69, 0x6e, 0x2d, 0x43, 0x6c, 0x61,
+ 0x73, 0x73, 0x3a, 0x20, 0x73, 0x68, 0x69, 0x72, 0x75, 0x64, 0x6f, 0x2e,
+ 0x55, 0x6e, 0x6c, 0x6f, 0x61, 0x64, 0x65, 0x64, 0x0d, 0x0a, 0x0d, 0x0a,
+ 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x21, 0x00, 0xbc, 0xe2, 0x68, 0x5c, 0xc0, 0x00, 0x00, 0x00, 0xc0, 0x00,
+ 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x73, 0x68, 0x69, 0x72, 0x75, 0x64,
+ 0x6f, 0x2f, 0x55, 0x6e, 0x6c, 0x6f, 0x61, 0x64, 0x65, 0x64, 0x2e, 0x63,
+ 0x6c, 0x61, 0x73, 0x73, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x00, 0x00, 0x34,
+ 0x00, 0x0c, 0x0a, 0x00, 0x02, 0x00, 0x03, 0x07, 0x00, 0x04, 0x0c, 0x00,
+ 0x05, 0x00, 0x06, 0x01, 0x00, 0x10, 0x6a, 0x61, 0x76, 0x61, 0x2f, 0x6c,
+ 0x61, 0x6e, 0x67, 0x2f, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x01, 0x00,
+ 0x06, 0x3c, 0x69, 0x6e, 0x69, 0x74, 0x3e, 0x01, 0x00, 0x03, 0x28, 0x29,
+ 0x56, 0x07, 0x00, 0x08, 0x01, 0x00, 0x10, 0x73, 0x68, 0x69, 0x72, 0x75,
+ 0x64, 0x6f, 0x2f, 0x55, 0x6e, 0x6c, 0x6f, 0x61, 0x64, 0x65, 0x64, 0x01,
+ 0x00, 0x04, 0x43, 0x6f, 0x64, 0x65, 0x01, 0x00, 0x07, 0x70, 0x72, 0x65,
+ 0x6d, 0x61, 0x69, 0x6e, 0x01, 0x00, 0x15, 0x28, 0x4c, 0x6a, 0x61, 0x76,
+ 0x61, 0x2f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x53, 0x74, 0x72, 0x69, 0x6e,
+ 0x67, 0x3b, 0x29, 0x56, 0x00, 0x31, 0x00, 0x07, 0x00, 0x02, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x05, 0x00, 0x06, 0x00, 0x01,
+ 0x00, 0x09, 0x00, 0x00, 0x00, 0x11, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00,
+ 0x00, 0x05, 0x2a, 0xb7, 0x00, 0x01, 0xb1, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x09, 0x00, 0x0a, 0x00, 0x0b, 0x00, 0x01, 0x00, 0x09, 0x00, 0x00, 0x00,
+ 0x0d, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0xb1, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x03, 0x14, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x00, 0x6d, 0x6f, 0x09, 0xd7,
+ 0x3a, 0x00, 0x00, 0x00, 0x3a, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x01, 0x00, 0x00,
+ 0x00, 0x00, 0x4d, 0x45, 0x54, 0x41, 0x2d, 0x49, 0x4e, 0x46, 0x2f, 0x4d,
+ 0x41, 0x4e, 0x49, 0x46, 0x45, 0x53, 0x54, 0x2e, 0x4d, 0x46, 0x50, 0x4b,
+ 0x01, 0x02, 0x14, 0x03, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x21, 0x00, 0xbc, 0xe2, 0x68, 0x5c, 0xc0, 0x00, 0x00, 0x00, 0xc0, 0x00,
+ 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xa4, 0x01, 0x6c, 0x00, 0x00, 0x00, 0x73, 0x68, 0x69, 0x72,
+ 0x75, 0x64, 0x6f, 0x2f, 0x55, 0x6e, 0x6c, 0x6f, 0x61, 0x64, 0x65, 0x64,
+ 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00,
+ 0x00, 0x00, 0x02, 0x00, 0x02, 0x00, 0x86, 0x00, 0x00, 0x00, 0x60, 0x01,
+ 0x00, 0x00, 0x00, 0x00,
+};
+
+int java_agent_path(const char *name, char *buf, size_t cap)
+{
+ if (strsprintf(buf, cap, "%s/%s.jar", JAVA_DIR, name) < 0)
+ return -ENAMETOOLONG;
+ return 0;
+}
+
+/*
+ * The label is what the seal protects: an unlabelled directory here is
+ * one root made, whose jars root could swap.
+ */
+static int java_dir_check(void)
+{
+ struct stat st;
+
+ if (lstat(JAVA_DIR, &st))
+ return -errno;
+ if (!S_ISDIR(st.st_mode) || st.st_uid || (st.st_mode & 0022) ||
+ !seal_parent_labeled(JAVA_DIR "/."))
+ return -EPERM;
+ return 0;
+}
+
+int java_agent_dir_prepare(void)
+{
+ int ret;
+
+ if (mkdir(JAVA_DIR, 0755)) {
+ if (errno != EEXIST)
+ return -errno;
+ return java_dir_check();
+ }
+ ret = chmod(JAVA_DIR, 0755) ? -errno : seal_label(JAVA_DIR);
+ if (ret) {
+ rmdir(JAVA_DIR);
+ return ret;
+ }
+ return 0;
+}
+
+int java_agent_install(const char *name, const void *jar, size_t len)
+{
+ char path[PATH_MAX];
+ int ret;
+
+ ret = java_agent_path(name, path, sizeof(path));
+ if (!ret)
+ ret = java_agent_dir_prepare();
+ if (!ret)
+ ret = seal_write_file_mode(path, jar, len, 0644);
+ return ret;
+}
+
+/* Whether the jar installed under name is the len bytes at jar. */
+static int jar_installed(const char *name, const void *jar, size_t len)
+{
+ char path[PATH_MAX];
+ size_t have_len = 0;
+ __u8 *have;
+ int fd, ret;
+
+ ret = java_agent_path(name, path, sizeof(path));
+ if (ret)
+ return ret;
+ fd = seal_open_read(path);
+ if (fd == -ENOENT)
+ return 0;
+ if (fd < 0)
+ return fd;
+ ret = read_fd(fd, path, UPATCH_FILE_MAX, &have, &have_len);
+ close(fd);
+ if (ret)
+ return ret;
+ ret = have_len == len && !memcmp(have, jar, len);
+ xfree(have, have_len + 1);
+ return ret;
+}
+
+int java_agent_retire(const char *name)
+{
+ char path[PATH_MAX];
+ int ret;
+
+ ret = java_agent_path(name, path, sizeof(path));
+ if (ret)
+ return ret;
+ if (access(path, F_OK))
+ return errno == ENOENT ? 0 : -errno;
+ ret = jar_installed(name, java_placeholder, sizeof(java_placeholder));
+ if (ret)
+ return min(ret, 0);
+ return seal_write_file_mode(path, java_placeholder,
+ sizeof(java_placeholder), 0644);
+}
+
+/* The sealed archive of name, opened: 0, or -ENOENT for none. */
+static int archive_open(const char *name, struct upatch *u)
+{
+ char path[PATH_MAX];
+ int fd, ret;
+
+ if (strsprintf(path, sizeof(path), "%s/%s.upatch", UPATCHES_DIR,
+ name) < 0)
+ return -ENAMETOOLONG;
+ fd = seal_open_read(path);
+ if (fd < 0)
+ return fd;
+ ret = upatch_open_fd(fd, u);
+ close(fd);
+ return ret;
+}
+
+static bool java_load(const struct upatch *u)
+{
+ return u->hdr.type == UPATCH_TYPE_JAVA && !upatch_is_unload(u);
+}
+
+/*
+ * 1 with *u open when the archive of name is a Java load; 0 when there is
+ * none, or one that is foreign, malformed or of another kind, which boot
+ * restore ignores too; -errno when that cannot be told.
+ */
+static int archived_java(const char *name, struct upatch *u)
+{
+ int ret = archive_open(name, u);
+
+ if (ret == -ENOENT || ret == -EPERM || ret == -EINVAL ||
+ ret == -EFBIG)
+ return 0;
+ if (ret)
+ return ret;
+ if (java_load(u))
+ return 1;
+ upatch_close(u);
+ return 0;
+}
+
+int java_agent_payload(const char *name,
+ __u8 payload[UPATCH_PAYLOAD_HASH_LEN])
+{
+ struct upatch u;
+ const void *jar;
+ __u32 len;
+ int ret;
+
+ ret = archived_java(name, &u);
+ if (ret <= 0)
+ return ret ? ret : -ENOENT;
+ jar = upatch_signed_jar(&u, &len);
+ if (!jar) {
+ upatch_close(&u);
+ return -ENOENT;
+ }
+ ret = jar_installed(name, jar, len);
+ if (ret == 1) {
+ memcpy(payload, u.hdr.payload_sha256, UPATCH_PAYLOAD_HASH_LEN);
+ ret = 0;
+ } else if (!ret) {
+ ret = -ESTALE;
+ }
+ upatch_close(&u);
+ return ret;
+}
+
+int java_tool_options(const char *const *names, size_t n, char *out,
+ size_t cap)
+{
+ size_t off = 0, i;
+ int w;
+
+ /* Appended, so that another environment.d file's options stay. */
+ w = strsprintf(out, cap,
+ "JAVA_TOOL_OPTIONS=\"${JAVA_TOOL_OPTIONS:+$JAVA_TOOL_OPTIONS }");
+ if (w < 0)
+ return w;
+ off = (size_t)w;
+ for (i = 0; i < n; i++) {
+ w = strsprintf(out + off, cap - off, "%s-javaagent:%s/%s.jar",
+ i ? " " : "", JAVA_DIR, names[i]);
+ if (w < 0)
+ return w;
+ off += (size_t)w;
+ }
+ w = strsprintf(out + off, cap - off, "\"\n");
+ if (w < 0)
+ return w;
+ return (int)(off + (size_t)w);
+}
+
+bool java_agent_loaded(const char *name)
+{
+ __u8 payload[UPATCH_PAYLOAD_HASH_LEN];
+
+ return !java_agent_payload(name, payload);
+}
+
+static int jar_select(const struct dirent *e)
+{
+ return name_has_suffix(e->d_name, strlen(e->d_name), ".jar");
+}
+
+/* cb for each jar under JAVA_DIR whose name is a upatch's, in name order. */
+static int jars_each(int (*cb)(const char *name, void *ctx), void *ctx)
+{
+ struct dirent **ents = NULL;
+ int n, i, ret = 0;
+
+ n = scandir(JAVA_DIR, &ents, jar_select, alphasort);
+ if (n < 0)
+ return errno == ENOENT ? 0 : -errno;
+ for (i = 0; i < n; i++) {
+ size_t len = strlen(ents[i]->d_name) - strlen(".jar");
+ char name[UPATCH_NAME_MAX + 1];
+
+ if (!ret && len < sizeof(name)) {
+ memcpy(name, ents[i]->d_name, len);
+ name[len] = '\0';
+ if (upatch_name_valid(name))
+ ret = cb(name, ctx);
+ }
+ libc_free(ents[i]);
+ }
+ libc_free(ents);
+ return ret;
+}
+
+struct loaded_walk {
+ int (*cb)(const char *name,
+ const __u8 payload[UPATCH_PAYLOAD_HASH_LEN], void *ctx);
+ void *ctx;
+};
+
+static int loaded_one(const char *name, void *ctx)
+{
+ __u8 payload[UPATCH_PAYLOAD_HASH_LEN];
+ struct loaded_walk *w = ctx;
+
+ if (java_agent_payload(name, payload))
+ return 0;
+ return w->cb(name, payload, w->ctx);
+}
+
+int java_agents_each_loaded(int (*cb)(const char *name,
+ const __u8 payload[UPATCH_PAYLOAD_HASH_LEN],
+ void *ctx),
+ void *ctx)
+{
+ struct loaded_walk w = { .cb = cb, .ctx = ctx };
+
+ return jars_each(loaded_one, &w);
+}
+
+struct unbacked_walk {
+ int (*cb)(const char *name, void *ctx);
+ void *ctx;
+ int n;
+};
+
+static int unbacked_one(const char *name, void *ctx)
+{
+ struct unbacked_walk *w = ctx;
+ int ret;
+
+ ret = jar_installed(name, java_placeholder, sizeof(java_placeholder));
+ if (ret)
+ return min(ret, 0);
+ if (java_agent_loaded(name))
+ return 0;
+ w->n++;
+ return w->cb ? w->cb(name, w->ctx) : 0;
+}
+
+int java_agents_unbacked(int (*cb)(const char *name, void *ctx), void *ctx)
+{
+ struct unbacked_walk w = { .cb = cb, .ctx = ctx };
+ int ret = jars_each(unbacked_one, &w);
+
+ return ret ? ret : w.n;
+}
+
+struct java_agents {
+ char **names;
+ size_t n;
+ size_t cap;
+};
+
+static void agents_free(struct java_agents *a)
+{
+ size_t i;
+
+ for (i = 0; i < a->n; i++)
+ xstrfree(a->names[i]);
+ xfree(a->names, a->cap * sizeof(*a->names));
+ a->names = NULL;
+ a->n = 0;
+}
+
+/*
+ * The jar file kept and named in a while its archive is a Java load, or
+ * while that cannot be told: a jar retired on a passing error would leave
+ * a measured agent missing with nothing measuring its removal.
+ */
+static int agent_sync_one(struct java_agents *a, const char *file)
+{
+ size_t len = strlen(file) - strlen(".jar");
+ struct upatch u;
+ char *name;
+ int ret;
+
+ name = xstrndup(file, len);
+ if (!name)
+ return -ENOMEM;
+ ret = upatch_name_valid(name) ? archived_java(name, &u) : 0;
+ if (ret == 1)
+ upatch_close(&u);
+ if (ret) {
+ a->names[a->n++] = name;
+ return min(ret, 0);
+ }
+ ret = java_agent_retire(name);
+ xstrfree(name);
+ return ret;
+}
+
+/*
+ * The jars under JAVA_DIR brought in line with the archive and named in a,
+ * in name order. 0, or the -errno when the directory cannot be read; the
+ * first error of a jar goes to *jar_err, the rest still done.
+ */
+static int agents_installed(struct java_agents *a, int *jar_err)
+{
+ struct dirent **ents = NULL;
+ int n, i, err;
+
+ a->names = NULL;
+ a->cap = 0;
+ a->n = 0;
+ *jar_err = 0;
+ n = scandir(JAVA_DIR, &ents, jar_select, alphasort);
+ if (n < 0)
+ return errno == ENOENT ? 0 : -errno;
+ a->cap = (size_t)n + 1;
+ a->names = xcalloc(a->cap, sizeof(*a->names));
+ for (i = 0; i < n; i++) {
+ err = a->names ? agent_sync_one(a, ents[i]->d_name) : -ENOMEM;
+ if (err && !*jar_err)
+ *jar_err = err;
+ libc_free(ents[i]);
+ }
+ libc_free(ents);
+ return a->names ? 0 : -ENOMEM;
+}
+
+static bool options_current(const char *want, size_t len)
+{
+ size_t have_len = 0;
+ char *have;
+ bool same;
+
+ if (read_file(JAVA_ENV_PATH, JAVA_OPTIONS_MAX, &have, &have_len))
+ return false;
+ same = have_len == len && !memcmp(have, want, len);
+ xfree(have, have_len + 1);
+ return same;
+}
+
+/* User managers read the directory as their user, whoever made it. */
+static int env_dir_prepare(void)
+{
+ if (mkdir(JAVA_ENV_DIR, 0755) && errno != EEXIST)
+ return -errno;
+ return chmod(JAVA_ENV_DIR, 0755) ? -errno : 0;
+}
+
+static int write_options(const struct java_agents *a)
+{
+ char *buf;
+ int len, ret;
+
+ if (!a->n) {
+ if (unlink(JAVA_ENV_PATH) && errno != ENOENT)
+ return -errno;
+ return 0;
+ }
+ buf = xmalloc(JAVA_OPTIONS_MAX);
+ if (!buf)
+ return -ENOMEM;
+ len = java_tool_options((const char *const *)a->names, a->n, buf,
+ JAVA_OPTIONS_MAX);
+ ret = min(len, 0);
+ if (!ret && !options_current(buf, (size_t)len)) {
+ ret = env_dir_prepare();
+ if (!ret)
+ ret = seal_write_file_mode(JAVA_ENV_PATH, buf,
+ (size_t)len, 0644);
+ }
+ xfree(buf, JAVA_OPTIONS_MAX);
+ return ret;
+}
+
+int java_agents_sync(void)
+{
+ struct java_agents a;
+ int ret, jar_err;
+
+ ret = agents_installed(&a, &jar_err);
+ if (ret)
+ return ret;
+ ret = write_options(&a);
+ agents_free(&a);
+ return jar_err ? jar_err : ret;
+}
diff --git a/util/java_agent.h b/util/java_agent.h
new file mode 100644
index 00000000..132f55a3
--- /dev/null
+++ b/util/java_agent.h
@@ -0,0 +1,96 @@
+/* SPDX-License-Identifier: BSD-2-Clause */
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * The Java agents a target runs: each loaded Java upatch's jar, sealed
+ * under JAVA_DIR, and the JAVA_TOOL_OPTIONS that names them.
+ */
+
+#ifndef SHIRUDO_UTIL_JAVA_AGENT_H
+#define SHIRUDO_UTIL_JAVA_AGENT_H
+
+#include <stdbool.h>
+#include <stddef.h>
+
+#include <shirudo/misc.h>
+#include <shirudo/upatch.h>
+
+struct upatch;
+
+/* JAVA_DIR/<name>.jar into buf, or -ENAMETOOLONG. */
+int java_agent_path(const char *name, char *buf, size_t cap) __must_check;
+
+/*
+ * JAVA_DIR made 0755 and labelled, or, when it is there, checked to be
+ * root's, not writable by others, and labelled. 0, -EPERM for one of
+ * someone else's making, or -errno.
+ */
+int __must_check java_agent_dir_prepare(void);
+
+/*
+ * The jar of name written sealed, readable by every JVM: JAVA_DIR as
+ * java_agent_dir_prepare() leaves it and the jar 0644. 0 or -errno.
+ */
+int java_agent_install(const char *name, const void *jar,
+ size_t len) __must_check;
+
+/*
+ * The jar of name replaced by one a JVM loads as an agent that does
+ * nothing: the options a user manager read before still name the jar, and
+ * a JVM does not start without it. 0, also when there was no jar.
+ */
+int java_agent_retire(const char *name) __must_check;
+
+/*
+ * The payload digest of the Java upatch loaded under name: its sealed
+ * archive is a Java load and its installed jar is the archived one, byte
+ * for byte. -ENOENT without such an archive, as when it is foreign,
+ * malformed or another kind of upatch, -ESTALE when the jar is missing or
+ * another, or another negative errno when that cannot be told.
+ */
+int java_agent_payload(const char *name,
+ __u8 payload[UPATCH_PAYLOAD_HASH_LEN]) __must_check;
+
+/*
+ * Whether java_agent_payload() finds name loaded. A check that cannot run
+ * counts as not loaded.
+ */
+bool java_agent_loaded(const char *name);
+
+/*
+ * cb for each Java upatch java_agent_payload() finds loaded, in name
+ * order, with its payload digest; a non-zero return of cb ends the walk
+ * with that value. 0, or -errno when the jar directory cannot be read.
+ */
+int java_agents_each_loaded(int (*cb)(const char *name,
+ const __u8 payload[UPATCH_PAYLOAD_HASH_LEN],
+ void *ctx),
+ void *ctx);
+
+/*
+ * cb for each jar that is an agent no archive backs: neither the
+ * placeholder nor the jar of the Java load archived under its name, as a
+ * load stopped before its archive leaves one. Their number, or the first
+ * non-zero return of cb, or -errno.
+ */
+int java_agents_unbacked(int (*cb)(const char *name, void *ctx), void *ctx);
+
+/*
+ * The JAVA_TOOL_OPTIONS line of an environment.d file for the n agents,
+ * each a -javaagent of its jar, in the order given, NUL-terminated in
+ * out. The length, or -E2BIG when it does not fit.
+ */
+int java_tool_options(const char *const *names, size_t n, char *out,
+ size_t cap) __must_check;
+
+/*
+ * The jars and the options brought in line with the archive: a jar whose
+ * archive is not a Java load is replaced with the placeholder, and the
+ * options name every other jar, the file rewritten only when that changes
+ * it and removed when no jar is named. A jar whose archive cannot be read
+ * is kept and named. 0, or the first -errno, the rest still done; the
+ * options are left alone when the jar directory cannot be read.
+ */
+int __must_check java_agents_sync(void);
+
+#endif /* SHIRUDO_UTIL_JAVA_AGENT_H */
diff --git a/util/keys.c b/util/keys.c
index fb68fe6b..4e829f3f 100644
--- a/util/keys.c
+++ b/util/keys.c
@@ -177,6 +177,18 @@ int keys_cert_der(const struct trusted_cert *c, const __u8 **der,
return -ENOKEY;
}
+const struct trusted_cert *keys_member(const struct trusted_set *set,
+ const __u8 fingerprint[32])
+{
+ size_t i;
+
+ for (i = 0; i < set->n; i++) {
+ if (!memcmp(set->certs[i].fingerprint, fingerprint, 32))
+ return &set->certs[i];
+ }
+ return NULL;
+}
+
int keys_cert_read(const struct trusted_cert *c,
struct cert *cert)
{
diff --git a/util/keys.h b/util/keys.h
index 659c51a0..ffa4f97e 100644
--- a/util/keys.h
+++ b/util/keys.h
@@ -76,6 +76,9 @@ struct cert;
*/
int keys_cert_der(const struct trusted_cert *c, const __u8 **der,
size_t *len);
+/* The member with that fingerprint, or NULL. */
+const struct trusted_cert *keys_member(const struct trusted_set *set,
+ const __u8 fingerprint[32]);
int keys_cert_read(const struct trusted_cert *c,
struct cert *cert);
diff --git a/util/measured.c b/util/measured.c
index a39469d2..ee8d7c62 100644
--- a/util/measured.c
+++ b/util/measured.c
@@ -5,7 +5,6 @@
#include <errno.h>
#include <limits.h>
#include <string.h>
-#include <sys/stat.h>
#include <sys/xattr.h>
#include <shirudo/misc.h>
@@ -459,27 +458,17 @@ int measured_unmeasured_pins(const struct measured_set *s,
return ret ? ret : unmeasured;
}
-int measured_unpinned(const struct measured_set *s,
- int (*cb)(const char *name, void *ctx), void *ctx)
+int measured_each(const struct measured_set *s,
+ int (*cb)(const char *name, const char *payload_hex,
+ void *ctx),
+ void *ctx)
{
- char dir[PATH_MAX];
- int ret = 0, n = 0;
- struct stat st;
+ int ret = 0;
size_t i;
- for (i = 0; i < s->n && !ret; i++) {
- if (upatch_pin_path(dir, sizeof(dir), s->entries[i].name,
- NULL) < 0)
- return -ENAMETOOLONG;
- if (!lstat(dir, &st))
- continue;
- if (errno != ENOENT)
- return -errno;
- n++;
- if (cb)
- ret = cb(s->entries[i].name, ctx);
- }
- return ret ? ret : n;
+ for (i = 0; i < s->n && !ret; i++)
+ ret = cb(s->entries[i].name, s->entries[i].payload_hex, ctx);
+ return ret;
}
int measured_unmeasured_archives(const struct measured_set *s,
diff --git a/util/measured.h b/util/measured.h
index c530896c..aa832a5e 100644
--- a/util/measured.h
+++ b/util/measured.h
@@ -65,12 +65,12 @@ int measured_unmeasured_archives(const struct measured_set *s,
void *ctx);
/*
- * The upatches the set holds without a pin directory: detached with no
- * unload of record, which only a task with runtime authority does. cb
- * runs for each; the number found, or -errno when a pin cannot be
- * looked up.
+ * cb for each member with its payload digest in hex, in the set's order;
+ * a non-zero return of cb ends the walk with that value.
*/
-int measured_unpinned(const struct measured_set *s,
- int (*cb)(const char *name, void *ctx), void *ctx);
+int measured_each(const struct measured_set *s,
+ int (*cb)(const char *name, const char *payload_hex,
+ void *ctx),
+ void *ctx);
#endif /* SHIRUDO_MEASURED_H */
diff --git a/util/paths.h b/util/paths.h
index e2968699..86e006b3 100644
--- a/util/paths.h
+++ b/util/paths.h
@@ -29,6 +29,16 @@
#define INITRD_KEYS_DIR "/etc/shirudo/keys"
#define INITRD_CERT_PATH INITRD_KEYS_DIR "/" CERT_FILE
#define UPATCHES_DIR VAR_LIB "/upatches"
+/*
+ * The jars of the loaded Java upatches, the one directory of sealed
+ * state a JVM reads, which boot restore writes again each boot: outside
+ * the state root, which stays closed to other users. The options a user
+ * manager's environment.d hands each JVM it starts live as long as the
+ * jars they name, so that options never outlive the jars across a boot.
+ */
+#define JAVA_DIR "/run/shirudo-java"
+#define JAVA_ENV_DIR "/run/environment.d"
+#define JAVA_ENV_PATH JAVA_ENV_DIR "/shirudo.conf"
#define LOCKS_DIR VAR_LIB "/locks"
#define EVENTLOG_PATH VAR_LIB "/eventlog"
/*
diff --git a/util/seal.c b/util/seal.c
index bb28ae1c..398b5d95 100644
--- a/util/seal.c
+++ b/util/seal.c
@@ -611,8 +611,8 @@ int seal_mkdir_p(const char *path, mode_t mode)
return 0;
}
-int seal_write_file(const char *path, const void *data, size_t len,
- mode_t mode)
+static int write_file(const char *path, const void *data, size_t len,
+ mode_t mode, bool exact)
{
char tmp[NAME_MAX + 1];
const char *name;
@@ -633,6 +633,8 @@ int seal_write_file(const char *path, const void *data, size_t len,
return ret;
}
ret = seal_inherit(dfd, fd);
+ if (!ret && exact && fchmod(fd, mode))
+ ret = -errno;
if (!ret)
ret = write_complete(fd, data, len);
if (!ret && fsync(fd))
@@ -648,3 +650,15 @@ int seal_write_file(const char *path, const void *data, size_t len,
close(dfd);
return ret;
}
+
+int seal_write_file(const char *path, const void *data, size_t len,
+ mode_t mode)
+{
+ return write_file(path, data, len, mode, false);
+}
+
+int seal_write_file_mode(const char *path, const void *data, size_t len,
+ mode_t mode)
+{
+ return write_file(path, data, len, mode, true);
+}
diff --git a/util/seal.h b/util/seal.h
index e0f09771..7a825843 100644
--- a/util/seal.h
+++ b/util/seal.h
@@ -77,6 +77,9 @@ bool seal_parent_labeled(const char *path);
int seal_write_file(const char *path, const void *data, size_t len,
mode_t mode);
+/* The same, with exactly that mode whatever the umask, before the rename. */
+int seal_write_file_mode(const char *path, const void *data, size_t len,
+ mode_t mode);
/*
* The lock file at path, created sealed when it is not there, held
diff --git a/util/upatch_verify.c b/util/upatch_verify.c
index 2f228ab8..6ddbedc4 100644
--- a/util/upatch_verify.c
+++ b/util/upatch_verify.c
@@ -19,6 +19,9 @@
#include "chain.h"
#include "hex.h"
+#include "java_agent.h"
+#include "keyring.h"
+#include "keys.h"
#include "malloc.h"
#include "measured.h"
#include "paths.h"
@@ -41,6 +44,84 @@ int upatch_payload_digest(const struct upatch *u,
upatch_data(u), u->hdr.data_len, out);
}
+static bool java_sections_complete(const struct upatch *u)
+{
+ __u32 len;
+
+ if (u->hdr.type != UPATCH_TYPE_JAVA ||
+ upatch_signed_type(u) != UPATCH_TYPE_JAVA || !upatch_name_signed(u))
+ return false;
+ if (upatch_is_unload(u))
+ return upatch_signed_unload_payload(u);
+ return upatch_signed_jar(u, &len);
+}
+
+/*
+ * The kernel trusts a BPF signer only through the .bpf keyring, so a
+ * Java signer has to be there too. Activation already refuses a set the
+ * ring does not hold; this keeps the Java check from resting on that.
+ */
+static int signer_enrolled(const struct trusted_set *set,
+ const __u8 fingerprint[32])
+{
+ const struct trusted_cert *member;
+ key_serial_t ring;
+ const __u8 *der;
+ size_t len;
+ int ret;
+
+ ring = keyring_bpf_serial();
+ if (ring < 0)
+ return ring;
+ member = keys_member(set, fingerprint);
+ if (!member)
+ return -EKEYREJECTED;
+ ret = keys_cert_der(member, &der, &len);
+ if (!ret)
+ ret = keyring_holds_cert(ring, der, len);
+ if (ret < 0)
+ return ret;
+ return ret ? 0 : -EKEYREJECTED;
+}
+
+static int java_signature_verify(const struct upatch *u)
+{
+ struct trusted_set *set;
+ __u8 signer[32];
+ int ret;
+
+ set = xcalloc(1, sizeof(*set));
+ if (!set)
+ return -ENOMEM;
+ ret = keys_load(RUNTIME_DIR "/keys", KEYS_REVOKED_DIR, true, set);
+ if (!ret && !set->n)
+ ret = -EKEYREJECTED;
+ if (!ret)
+ ret = keys_verify_signature(set, upatch_data(u),
+ u->hdr.data_len,
+ upatch_signature(u),
+ u->hdr.signature_len, signer);
+ if (!ret)
+ ret = signer_enrolled(set, signer);
+ xfree(set, sizeof(*set));
+ return ret;
+}
+
+int java_upatch_verify(const struct upatch *u)
+{
+ __u8 digest[UPATCH_PAYLOAD_HASH_LEN];
+ int ret;
+
+ if (!java_sections_complete(u))
+ return -EBADMSG;
+ ret = upatch_payload_digest(u, digest);
+ if (ret)
+ return ret;
+ if (memneq_explicit(digest, u->hdr.payload_sha256, sizeof(digest)))
+ return -EBADMSG;
+ return java_signature_verify(u);
+}
+
int upatch_verify_fd(int fd, const __u8 payload[UPATCH_PAYLOAD_HASH_LEN],
struct upatch *out)
{
@@ -242,6 +323,53 @@ int upatch_xdp_each_uncovered(const char *name, const struct prog_spec *specs,
return 0;
}
+int upatch_loaded_payload(const char *name,
+ __u8 payload[UPATCH_PAYLOAD_HASH_LEN])
+{
+ if (!upatch_pin_payload(name, payload))
+ return 0;
+ return java_agent_payload(name, payload);
+}
+
+struct unpinned_walk {
+ int (*cb)(const char *name, void *ctx);
+ void *ctx;
+ int n;
+};
+
+static int unpinned_one(const char *name, const char *payload_hex,
+ void *ctx)
+{
+ char hex[2 * UPATCH_PAYLOAD_HASH_LEN + 1];
+ __u8 payload[UPATCH_PAYLOAD_HASH_LEN];
+ struct unpinned_walk *w = ctx;
+ char dir[PATH_MAX];
+ struct stat st;
+
+ if (upatch_pin_path(dir, sizeof(dir), name, NULL) < 0)
+ return -ENAMETOOLONG;
+ if (!lstat(dir, &st))
+ return 0;
+ if (errno != ENOENT)
+ return -errno;
+ if (!upatch_loaded_payload(name, payload)) {
+ hex_encode(payload, sizeof(payload), hex);
+ if (!strcmp(hex, payload_hex))
+ return 0;
+ }
+ w->n++;
+ return w->cb ? w->cb(name, w->ctx) : 0;
+}
+
+int upatch_unpinned(const struct measured_set *s,
+ int (*cb)(const char *name, void *ctx), void *ctx)
+{
+ struct unpinned_walk w = { .cb = cb, .ctx = ctx };
+ int ret = measured_each(s, unpinned_one, &w);
+
+ return ret ? ret : w.n;
+}
+
bool upatch_pin_measured(const struct measured_set *s, const char *name,
__u8 payload[UPATCH_PAYLOAD_HASH_LEN])
{
diff --git a/util/upatch_verify.h b/util/upatch_verify.h
index 25a63ed8..c4e569c0 100644
--- a/util/upatch_verify.h
+++ b/util/upatch_verify.h
@@ -26,6 +26,17 @@ struct xdp_device;
int upatch_payload_digest(const struct upatch *u,
__u8 out[UPATCH_PAYLOAD_HASH_LEN]) __must_check;
+/*
+ * What the kernel checks of a BPF upatch, checked in userspace for a Java
+ * one, which has no loader: the signed type and name, the section its
+ * direction needs, the payload digest, and the signature over the data
+ * under a certificate of the runtime's set that the .bpf keyring still
+ * holds. -EBADMSG for a malformed or mismatched upatch, -EKEYREJECTED
+ * for a signature no such certificate made, or another negative errno
+ * when the check could not run.
+ */
+int java_upatch_verify(const struct upatch *u) __must_check;
+
/*
* 0 with the artifact open in *out, -ESTALE when it is not what payload
* names, or another negative errno when the check itself could not run.
@@ -68,6 +79,24 @@ int upatch_xdp_each_uncovered(const char *name, const struct prog_spec *specs,
struct measured_set;
+/*
+ * The payload loaded under name: the one its pins record, else the
+ * archived one of a Java upatch whose jar is installed as archived.
+ * -ENOENT when neither, -ESTALE for a Java load whose jar is missing or
+ * another, or another negative errno when that cannot be told.
+ */
+int upatch_loaded_payload(const char *name,
+ __u8 payload[UPATCH_PAYLOAD_HASH_LEN]) __must_check;
+
+/*
+ * The upatches the set holds that do not run: no pin directory, and for a
+ * Java one no jar installed as archived; a BPF one is detached with no
+ * unload of record, which only a task with runtime authority does. cb runs
+ * for each; the number found, or -errno when a pin cannot be looked up.
+ */
+int upatch_unpinned(const struct measured_set *s,
+ int (*cb)(const char *name, void *ctx), void *ctx);
+
/*
* Whether the set holds name with the payload its pin directory records,
* which is left in payload when the directory records one.