Skip to content

eBPF-based security platform

image: build and verify images with veritysetup

KP Singhc47c3bc7286a
diff --git a/.github/scripts/vm-toolchain.sh b/.github/scripts/vm-toolchain.sh
index 49b6e9d4..ad231175 100755
--- a/.github/scripts/vm-toolchain.sh
+++ b/.github/scripts/vm-toolchain.sh
@@ -37,6 +37,8 @@ apt-get install -y --no-install-recommends \
build-essential \
ca-certificates \
clang \
+ cryptsetup-bin \
+ e2fsprogs \
llvm \
curl \
git \
diff --git a/.github/workflows/deb.yml b/.github/workflows/deb.yml
index 97d836dc..ee4a502a 100644
--- a/.github/workflows/deb.yml
+++ b/.github/workflows/deb.yml
@@ -59,6 +59,8 @@ jobs:
build-essential \
ca-certificates \
clang \
+ cryptsetup-bin \
+ e2fsprogs \
llvm \
python3 \
pkg-config \
@@ -296,7 +298,7 @@ jobs:
- name: Install the build dependencies
run: |
dnf -q install -y gcc make pkgconf-pkg-config git python3 rpm-build \
- clang llvm openssl openssl-devel libcurl-devel tpm2-tss-devel \
+ clang llvm cryptsetup openssl openssl-devel libcurl-devel tpm2-tss-devel \
elfutils-libelf-devel zlib-ng-compat-devel luajit-devel jq
- name: Check out repository
diff --git a/.github/workflows/sanitizers.yml b/.github/workflows/sanitizers.yml
index f6997cc0..06c2e20d 100644
--- a/.github/workflows/sanitizers.yml
+++ b/.github/workflows/sanitizers.yml
@@ -53,6 +53,8 @@ jobs:
build-essential \
ca-certificates \
clang \
+ cryptsetup-bin \
+ e2fsprogs \
libclang-rt-21-dev \
llvm \
curl \
diff --git a/Makefile.shirudo b/Makefile.shirudo
index f314f3b4..193cf515 100644
--- a/Makefile.shirudo
+++ b/Makefile.shirudo
@@ -193,6 +193,7 @@ UTIL_SRCS := \
util/kernel_build_id.c \
util/kernel_release.c \
util/config.c \
+ util/config_image.c \
util/bpm_source_config.c \
util/eventlog.c \
util/json.c \
@@ -223,6 +224,7 @@ BUILTIN_SRCS := \
builtin-status.c \
builtin-keys.c \
builtin-config.c \
+ builtin-image.c \
builtin-upatch.c \
builtin-bpm.c \
builtin-attest.c \
@@ -257,7 +259,8 @@ BUILD_SRCS := \
tools/shirudo-build/vmlinux.c \
tools/shirudo-build/bpm-build.c \
tools/shirudo-build/bpm-publish.c \
- tools/shirudo-build/vouch.c
+ tools/shirudo-build/vouch.c \
+ tools/shirudo-build/image.c
# ----- derived names ----------------------------------------------
@@ -410,9 +413,9 @@ build/target/util/loader.o: $(BPF_OBJS)
# --unload directive emission path), and the OCI client for the
# operator-only `bpm build|push|tree append`. Not linked into the core
# shirudo binary.
-tools/shirudo-build/shirudo-build: $(BUILD_OBJS) util/sign.o \
+tools/shirudo-build/shirudo-build: $(BUILD_OBJS) util/sign.o util/config_image.o \
util/log.o util/json.o util/loader.o \
- util/io.o util/malloc.o util/paths.o \
+ util/io.o util/malloc.o util/paths.o util/config.o \
util/upatch.o util/timefmt.o \
util/elf_target.o util/hex.o util/keys.o \
util/seal.o util/harden.o util/string.o \
@@ -577,7 +580,7 @@ testing/helper/test-conditions: testing/helper/test-conditions.c util/conditions
# util/config.o resolves config_load(), called by tpm.o.
# The register code pulls in the eventlog, which pulls in the seal
# label writer and the JSON codec.
-REGISTER_OBJS := util/chain.o util/tpm.o util/tpm_wire.o util/eventlog.o \
+REGISTER_OBJS := util/config_image.o util/chain.o util/tpm.o util/tpm_wire.o util/eventlog.o \
util/timefmt.o \
util/hex.o util/crypto_openssl.o util/json.o util/string.o \
util/io.o util/seal.o util/config.o util/log.o util/malloc.o \
@@ -701,6 +704,11 @@ testing/upatch/kernel-obs/exec/exec-paths: testing/upatch/kernel-obs/exec/exec_p
@printf ' CC $@\n'
$(Q)$(CC) $(CFLAGS) -pthread -o $@ $^
+
+
+
+
+
test-helpers: $(TEST_HELPERS)
# ----- fuzzing ----------------------------------------------------
diff --git a/builtin-image.c b/builtin-image.c
new file mode 100644
index 00000000..d48a6270
--- /dev/null
+++ b/builtin-image.c
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "builtin.h"
+#include "util/log.h"
+#include "util/malloc.h"
+
+static void image_help(void)
+{
+ fprintf(stderr,
+ "usage: shirudo image build [image builder options]\n"
+ " shirudo image verify <prefix> --cert <certificate>\n");
+}
+
+int cmd_image(int argc, const char **argv)
+{
+ int rc;
+
+ if (argc == 2 && !strcmp(argv[1], "--list-cmds")) {
+ puts("build verify");
+ return 0;
+ }
+ if (argc < 2 || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) {
+ image_help();
+ return argc < 2 ? 2 : 0;
+ }
+ if (!strcmp(argv[1], "build") || !strcmp(argv[1], "verify")) {
+ char **helper;
+ size_t bytes;
+ int i;
+
+ bytes = ((size_t)argc + 2) * sizeof(*helper);
+ helper = xcalloc((size_t)argc + 2, sizeof(*helper));
+ if (!helper)
+ return 1;
+ helper[1] = "image";
+ for (i = 1; i < argc; i++)
+ helper[i + 1] = (char *)argv[i];
+ rc = shirudo_build_exec(!strcmp(argv[1], "build") ?
+ "image build" : "image verify", helper);
+ xfree(helper, bytes);
+ return rc;
+ }
+ image_help();
+ return 2;
+}
diff --git a/builtin.h b/builtin.h
index 7bdf4939..fafb50be 100644
--- a/builtin.h
+++ b/builtin.h
@@ -49,5 +49,6 @@ int cmd_attest(int argc, const char **argv);
int cmd_version(int argc, const char **argv);
int cmd_keys(int argc, const char **argv);
int cmd_config(int argc, const char **argv);
+int cmd_image(int argc, const char **argv);
#endif /* SHIRUDO_BUILTIN_H */
diff --git a/completion/shirudo.bash b/completion/shirudo.bash
index 77503a7b..84d39c76 100644
--- a/completion/shirudo.bash
+++ b/completion/shirudo.bash
@@ -31,6 +31,20 @@ _shirudo()
cmd="${COMP_WORDS[1]}"
sub="${COMP_WORDS[2]}"
case "$cmd" in
+ image)
+ if (( cword == 2 )); then
+ local subs
+ subs=$("$bin" image --list-cmds 2>/dev/null)
+ COMPREPLY=( $(compgen -W "$subs" -- "$cur") )
+ elif [[ $cur == -* && $sub == build ]]; then
+ COMPREPLY=( $(compgen -W "-o --kind --keys-dir --key \
+ --cert --salt" -- "$cur") )
+ elif [[ $cur == -* && $sub == verify ]]; then
+ COMPREPLY=( $(compgen -W "--cert" -- "$cur") )
+ else
+ COMPREPLY=( $(compgen -f -- "$cur") )
+ fi
+ ;;
upatch)
if (( cword == 2 )); then
local subs
@@ -127,7 +141,8 @@ _shirudo()
COMPREPLY=( $(compgen -W "--evidence= --nonce= --ak-name= \
--cert= --upatch= --expect= --tree-root= \
--expect-chain= --expect-pcr= --expect-credential= \
- --allow-runtime-events --strict-anchor" -- "$cur") )
+ --allow-runtime-events --strict-anchor \
+ --expect-config-root= --expect-config-pcr=" -- "$cur") )
elif [[ $sub == predict ]]; then
COMPREPLY=( $(compgen -W "--cert= --upatch= --expect= \
--tree-root= --event=" -- "$cur") )
diff --git a/packaging/deb/builddeb.sh b/packaging/deb/builddeb.sh
index 658a64c8..c4084195 100755
--- a/packaging/deb/builddeb.sh
+++ b/packaging/deb/builddeb.sh
@@ -59,8 +59,8 @@ esac
depends=$("$here/depends.sh" $bins || true)
if [ "$role" = operator ]; then
- # shirudo-build execs clang to compile .bpf.c upatches into objects.
- depends="${depends:+$depends, }clang, llvm"
+ # Operator-only compilers and the standard image format/verify tool.
+ depends="${depends:+$depends, }clang, llvm, cryptsetup-bin"
fi
# Installed-Size is in KiB, computed before DEBIAN/ exists.
diff --git a/packaging/rpm/buildrpm.sh b/packaging/rpm/buildrpm.sh
index 33a1939e..f4e16315 100755
--- a/packaging/rpm/buildrpm.sh
+++ b/packaging/rpm/buildrpm.sh
@@ -85,8 +85,8 @@ dirs=$(cd "$stage" && find . -mindepth 1 -type d -path '*/shirudo*' | sed 's#^\.
printf 'Packager: %s\n' "$maint"
printf 'Conflicts: %s\n' "$other"
if [ "$role" = operator ]; then
- # shirudo-build execs clang to compile .bpf.c upatches.
- printf 'Requires: clang, llvm\n'
+ # Operator-only compilers and the standard image format/verify tool.
+ printf 'Requires: clang, llvm, cryptsetup\n'
fi
printf '\n%%description\n'
if [ "$role" = target ]; then
diff --git a/shirudo.c b/shirudo.c
index d4e9df5b..dcd65063 100644
--- a/shirudo.c
+++ b/shirudo.c
@@ -42,6 +42,8 @@ static const struct cmd commands[] = {
{ "genkey", cmd_genkey, GROUP_OPERATOR, "generate the signing key + cert" },
{ "build", cmd_build, GROUP_OPERATOR, "compile + sign a .upatch" },
+ { "image", cmd_image, GROUP_LOCAL,
+ "build and verify dm-verity images" },
{ "init", cmd_init, GROUP_TARGET,
"bootstrap shirudo enforcement on this target" },
{ "upatch", cmd_upatch, GROUP_TARGET,
diff --git a/tools/gen-image/shirudo-gen-image b/tools/gen-image/shirudo-gen-image
new file mode 100755
index 00000000..f0e7074a
--- /dev/null
+++ b/tools/gen-image/shirudo-gen-image
@@ -0,0 +1,82 @@
+#!/bin/bash
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+set -euo pipefail
+
+usage()
+{
+ cat <<'EOF'
+usage: shirudo-gen-image --source <directory> --output <prefix>
+ --keys-dir <operator-key-directory> [--kind config|runtime] [--size <MiB>]
+ [--builder <shirudo-build>]
+
+Build an ext4 image and detached signed dm-verity metadata on the operator.
+Writes <prefix>.img, <prefix>.verity, <prefix>.roothash and <prefix>.p7s.
+The source directory is the filesystem root; it is not the host rootfs.
+No existing output file is replaced. The private key never enters the image.
+EOF
+}
+
+die()
+{
+ printf 'shirudo-gen-image: %s\n' "$*" >&2
+ exit 1
+}
+
+source_dir=
+output=
+keys_dir=
+kind=config
+size=64
+builder=${SHIRUDO_BUILD:-shirudo-build}
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --source) source_dir=${2:?}; shift 2 ;;
+ --output) output=${2:?}; shift 2 ;;
+ --keys-dir) keys_dir=${2:?}; shift 2 ;;
+ --kind) kind=${2:?}; shift 2 ;;
+ --size) size=${2:?}; shift 2 ;;
+ --builder) builder=${2:?}; shift 2 ;;
+ -h|--help) usage; exit 0 ;;
+ *) usage >&2; die "unknown option: $1" ;;
+ esac
+done
+
+[ -n "$source_dir" ] && [ -d "$source_dir" ] || die '--source needs a directory'
+[ -n "$output" ] || die '--output is required'
+[ -n "$keys_dir" ] && [ -d "$keys_dir" ] || die '--keys-dir needs a directory'
+case "$kind" in config|runtime) ;; *) die '--kind must be config or runtime' ;; esac
+case "$size" in ''|*[!0-9]*) die '--size must be an integer in MiB' ;; esac
+[ "${#size}" -le 7 ] && [ "$size" -ge 8 ] && [ "$size" -le 1048576 ] ||
+ die '--size must be between 8 and 1048576 MiB'
+command -v veritysetup >/dev/null || die 'install veritysetup (cryptsetup-bin or cryptsetup)'
+command -v mkfs.ext4 >/dev/null || die 'install e2fsprogs (mkfs.ext4)'
+command -v "$builder" >/dev/null || die 'shirudo-build not found; use --builder'
+
+source_dir=$(realpath "$source_dir")
+keys_dir=$(realpath "$keys_dir")
+case "$keys_dir/" in "$source_dir/"*) die 'operator keys must be outside the image source' ;; esac
+for suffix in .img .verity .roothash .p7s; do
+ [ ! -e "$output$suffix" ] && [ ! -L "$output$suffix" ] ||
+ die "output already exists: $output$suffix"
+done
+if find "$source_dir" -type f -name signing_key.pem -print -quit | grep -q .; then
+ die 'the image source contains a private signing key'
+fi
+if [ "$kind" = config ] && find "$source_dir" -type l -print -quit | grep -q .; then
+ die 'config images must not contain symbolic links'
+fi
+if find "$source_dir" ! -type d ! -type f ! -type l -print -quit | grep -q .; then
+ die 'the image source contains a special file'
+fi
+
+work=$(mktemp -d)
+trap 'rm -rf "$work"' EXIT
+truncate -s "${size}M" "$work/filesystem.img"
+mkfs.ext4 -q -F -b 4096 -O '^has_journal' -E root_owner=0:0 \
+ -d "$source_dir" "$work/filesystem.img"
+"$builder" image build "$work/filesystem.img" -o "$output" \
+ --kind "$kind" --keys-dir "$keys_dir"
+"$builder" image verify "$output" --cert "$keys_dir/cert.der" >/dev/null
diff --git a/tools/gen-image/shirudo-gen-runtime b/tools/gen-image/shirudo-gen-runtime
new file mode 100755
index 00000000..04f3cdb5
--- /dev/null
+++ b/tools/gen-image/shirudo-gen-runtime
@@ -0,0 +1,127 @@
+#!/bin/bash
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+set -euo pipefail
+
+usage()
+{
+ cat <<'EOF'
+usage: shirudo-gen-runtime --binary <shirudo-target> --bootstrap-conf <file>
+ --cert <initial-BPF-cert.der> --config-cert <config-cert.der>
+ --output <prefix> --keys-dir <operator-key-directory>
+ [--size <MiB>] [--builder <shirudo-build>] [--unit-output <file>]
+ [--extra-binary <trusted-ELF>]
+
+Package the trusted executable, its complete dynamic-library closure,
+authenticated bootstrap settings and public certificates into a runtime image.
+The input binary must be trusted: ldd invokes its dynamic loader on the operator.
+EOF
+}
+
+die()
+{
+ printf 'shirudo-gen-runtime: %s\n' "$*" >&2
+ exit 1
+}
+
+binary=
+conf=
+cert=
+config_cert=
+output=
+keys_dir=
+size=128
+builder=${SHIRUDO_BUILD:-shirudo-build}
+unit_output=
+extra_binaries=()
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --binary) binary=${2:?}; shift 2 ;;
+ --bootstrap-conf) conf=${2:?}; shift 2 ;;
+ --cert) cert=${2:?}; shift 2 ;;
+ --config-cert) config_cert=${2:?}; shift 2 ;;
+ --output) output=${2:?}; shift 2 ;;
+ --keys-dir) keys_dir=${2:?}; shift 2 ;;
+ --size) size=${2:?}; shift 2 ;;
+ --builder) builder=${2:?}; shift 2 ;;
+ --unit-output) unit_output=${2:?}; shift 2 ;;
+ --extra-binary) extra_binaries+=("${2:?}"); shift 2 ;;
+ -h|--help) usage; exit 0 ;;
+ *) usage >&2; die "unknown option: $1" ;;
+ esac
+done
+for file in "$binary" "$conf" "$cert" "$config_cert"; do
+ [ -n "$file" ] && [ -f "$file" ] || die 'binary, bootstrap config and both public certificates are required'
+done
+[ -n "$output" ] && [ -n "$keys_dir" ] || die '--output and --keys-dir are required'
+command -v readelf >/dev/null || die 'install binutils (readelf)'
+command -v ldd >/dev/null || die 'ldd is required on the operator'
+interpreter=$(LC_ALL=C readelf -l "$binary" |
+ sed -n 's/.*Requesting program interpreter: \([^]]*\)].*/\1/p')
+[ -n "$interpreter" ] && [ "${interpreter:0:1}" = / ] ||
+ die 'expected a dynamically linked target ELF with an absolute interpreter'
+[ -f "$interpreter" ] || die "interpreter not found: $interpreter"
+
+work=$(mktemp -d)
+trap 'rm -rf "$work"' EXIT
+mkdir -p "$work/root/usr/bin" "$work/root/etc/shirudo" "$work/root/keys"
+install -m 0755 "$binary" "$work/root/usr/bin/shirudo"
+install -m 0644 "$conf" "$work/root/etc/shirudo/shirudo.conf"
+install -m 0644 "$cert" "$work/root/keys/cert.der"
+install -m 0644 "$config_cert" "$work/root/etc/shirudo/config-cert.der"
+LC_ALL=C ldd "$binary" >"$work/ldd" || die 'could not resolve target libraries'
+printf '%s\n' "$interpreter" >"$work/interpreters"
+for extra in "${extra_binaries[@]}"; do
+ [ -f "$extra" ] && [ -x "$extra" ] || die "extra binary not executable: $extra"
+ name=$(basename "$extra")
+ [ ! -e "$work/root/usr/bin/$name" ] || die "duplicate executable name: $name"
+ install -m 0755 "$extra" "$work/root/usr/bin/$name"
+ LC_ALL=C readelf -h "$extra" >/dev/null || die "extra binary is not ELF: $extra"
+ extra_interpreter=$(LC_ALL=C readelf -l "$extra" |
+ sed -n 's/.*Requesting program interpreter: \([^]]*\)\].*/\1/p')
+ if [ -n "$extra_interpreter" ]; then
+ printf '%s\n' "$extra_interpreter" >>"$work/interpreters"
+ fi
+ if LC_ALL=C readelf -d "$extra" | grep '(NEEDED)' >/dev/null; then
+ LC_ALL=C ldd "$extra" >>"$work/ldd" || die "could not resolve libraries: $extra"
+ fi
+done
+! grep -q 'not found' "$work/ldd" || die 'target libraries are missing'
+cp "$work/interpreters" "$work/libraries"
+awk '/^[[:space:]]*\// { print $1 } /=> \// { print $3 }' \
+ "$work/ldd" >>"$work/libraries"
+sort -u "$work/libraries" -o "$work/libraries"
+library_path=
+while IFS= read -r lib; do
+ [ -f "$lib" ] && [ "${lib:0:1}" = / ] || die "bad library path: $lib"
+ mkdir -p "$work/root$(dirname "$lib")"
+ cp -L "$lib" "$work/root$lib"
+ directory="/run/shirudo/runtime$(dirname "$lib")"
+ case ":$library_path:" in *":$directory:"*) ;;
+ *) library_path=${library_path:+$library_path:}$directory ;; esac
+done <"$work/libraries"
+
+here=$(cd "$(dirname "$0")" && pwd)
+"$here/shirudo-gen-image" --source "$work/root" --output "$output" \
+ --keys-dir "$keys_dir" --kind runtime --size "$size" --builder "$builder"
+printf 'Runtime invocation (after the authenticated image is mounted):\n' >&2
+printf '%q --inhibit-cache --library-path %q %q init\n' \
+ "/run/shirudo/runtime$interpreter" "$library_path" \
+ /run/shirudo/runtime/usr/bin/shirudo >&2
+
+if [ -n "$unit_output" ]; then
+ [ ! -e "$unit_output" ] && [ ! -L "$unit_output" ] || die "unit output already exists: $unit_output"
+ case "$interpreter$library_path" in *[[:space:]\\\"%]*) die 'runtime paths cannot be encoded in a systemd ExecStart' ;; esac
+ (
+ set -o noclobber
+ cat >"$unit_output" <<EOF
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+[Service]
+EnvironmentFile=
+ExecStart=
+ExecStart=/run/shirudo/runtime$interpreter --inhibit-cache --library-path $library_path /run/shirudo/runtime/usr/bin/shirudo init
+EOF
+ )
+fi
diff --git a/tools/shirudo-build/compile.c b/tools/shirudo-build/compile.c
index 4234df02..11cf5ee2 100644
--- a/tools/shirudo-build/compile.c
+++ b/tools/shirudo-build/compile.c
@@ -2,9 +2,8 @@
/*
* Copyright (c) 2026 Authors of shirudo
*
- * execv of clang -target bpf for .bpf.c -> .bpf.o. This is the only
- * subprocess in shirudo, by design. The clang path is hardcoded at
- * build time; PATH is never consulted.
+ * Operator-side execv of clang -target bpf for .bpf.c -> .bpf.o.
+ * The clang path is hardcoded at build time; PATH is never consulted.
*/
#include <errno.h>
diff --git a/tools/shirudo-build/image.c b/tools/shirudo-build/image.c
new file mode 100644
index 00000000..e47b8db8
--- /dev/null
+++ b/tools/shirudo-build/image.c
@@ -0,0 +1,403 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include <shirudo/misc.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <openssl/rand.h>
+
+#include "bpm.h"
+#include "config_image.h"
+#include "crypto.h"
+#include "hex.h"
+#include "image.h"
+#include "io.h"
+#include "log.h"
+#include "paths.h"
+#include "sign.h"
+
+static void image_usage(FILE *fp)
+{
+ fprintf(fp, "usage: shirudo-build image build <filesystem.img> -o "
+ "<prefix>\n"
+ " [--kind config|runtime] [--keys-dir <dir>]\n"
+ " [--key <private.pem>] [--cert <cert.der>] [--salt "
+ "<64-hex>]\n"
+ "Writes <prefix>.img/.verity/.roothash/.p7s; existing files "
+ "are refused.\n"
+ "Input is a 4096-byte-aligned ext4 filesystem image.\n"
+ " shirudo-build image verify <prefix> --cert <cert.der>\n"
+ "Build and offline verification require veritysetup.\n");
+}
+
+static int image_output_path(char *path, size_t cap, const char *prefix,
+ const char *suffix)
+{
+ int n = snprintf(path, cap, "%s%s", prefix, suffix);
+
+ return n < 0 || (size_t)n >= cap ? -ENAMETOOLONG : 0;
+}
+
+static int copy_image(int input_fd, int output_fd, __u64 size)
+{
+ __u8 buf[65536];
+ __u64 done = 0;
+ size_t want;
+ ssize_t n;
+ int rc;
+
+ while (done < size) {
+ want = size - done < sizeof(buf) ? size - done : sizeof(buf);
+ n = read(input_fd, buf, want);
+ if (n < 0) {
+ if (errno == EINTR)
+ continue;
+ return -errno;
+ }
+ if (!n)
+ return -EIO;
+ rc = write_complete(output_fd, buf, n);
+ if (rc)
+ return rc;
+ done += n;
+ }
+ do {
+ n = read(input_fd, buf, 1);
+ } while (n < 0 && errno == EINTR);
+ return n < 0 ? -errno : n ? -EFBIG : 0;
+}
+
+/* Only the operator invokes veritysetup; inherited FDs pin its inputs. */
+static int run_veritysetup(int data_fd, int hash_fd, int root_fd,
+ const struct shirudo_config_image *image)
+{
+ char root_path[80], data_path[40], hash_path[40], blocks[48];
+ char salt[72], root[65];
+ pid_t pid;
+ int status;
+
+ snprintf(data_path, sizeof(data_path), "/proc/self/fd/%d", data_fd);
+ snprintf(hash_path, sizeof(hash_path), "/proc/self/fd/%d", hash_fd);
+ snprintf(root_path, sizeof(root_path),
+ "--root-hash-file=/proc/self/fd/%d", root_fd);
+ snprintf(blocks, sizeof(blocks), "--data-blocks=%llu",
+ (__u64)image->data_blocks);
+ memcpy(salt, "--salt=", 7);
+ hex_encode(image->salt, sizeof(image->salt), salt + 7);
+ hex_encode(image->root_hash, sizeof(image->root_hash), root);
+ pid = fork();
+ if (pid < 0)
+ return -errno;
+ if (!pid) {
+ const char *const format_args[] = {
+ "veritysetup", "format", "--format=1", "--hash=sha256",
+ "--data-block-size=4096", "--hash-block-size=4096",
+ "--hash-offset=0", blocks, salt,
+ data_path, hash_path, root_path, NULL,
+ };
+ const char *const verify_args[] = {
+ "veritysetup", "verify", "--hash-offset=0",
+ data_path, hash_path, root, NULL,
+ };
+ int null_fd;
+
+ if (fcntl(data_fd, F_SETFD, 0) || fcntl(hash_fd, F_SETFD, 0) ||
+ (root_fd >= 0 && fcntl(root_fd, F_SETFD, 0)))
+ _exit(126);
+ null_fd = open("/dev/null", O_WRONLY | O_CLOEXEC);
+ if (null_fd < 0 || dup2(null_fd, STDOUT_FILENO) < 0)
+ _exit(126);
+ close(null_fd);
+ execvp("veritysetup", (char *const *)(root_fd >= 0 ?
+ format_args : verify_args));
+ pr_err("veritysetup: %s; install the operator veritysetup tool",
+ strerror(errno));
+ _exit(127);
+ }
+ while (waitpid(pid, &status, 0) < 0)
+ if (errno != EINTR)
+ return -errno;
+ if (!WIFEXITED(status))
+ return -EIO;
+ if (WEXITSTATUS(status) == 127)
+ return -ENOENT;
+ return WEXITSTATUS(status) ? -EIO : 0;
+}
+
+static int format_image(int data_fd, int hash_fd, __u64 size,
+ const __u8 salt[32],
+ struct shirudo_config_image *image)
+{
+ char root[66];
+ ssize_t n;
+ int fd, rc;
+
+ *image = (struct shirudo_config_image) {
+ .data_blocks = size / SHIRUDO_CONFIG_IMAGE_BLOCK_SIZE,
+ };
+ memcpy(image->salt, salt, sizeof(image->salt));
+ fd = memfd_create("shirudo-verity-root", MFD_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+ rc = run_veritysetup(data_fd, hash_fd, fd, image);
+ if (rc)
+ goto out;
+ do {
+ n = pread(fd, root, sizeof(root), 0);
+ } while (n < 0 && errno == EINTR);
+ if (n != 64 && (n != 65 || root[64] != '\n')) {
+ rc = n < 0 ? -errno : -EINVAL;
+ goto out;
+ }
+ rc = shirudo_config_image_read_header(hash_fd, image);
+ if (rc)
+ goto out;
+ root[64] = 0;
+ rc = hex_decode(root, image->root_hash,
+ sizeof(image->root_hash));
+ if (rc)
+ goto out;
+ rc = shirudo_config_image_check_files(data_fd, hash_fd, image);
+out:
+ close(fd);
+ return rc;
+}
+
+static int verify_root_signature(const char root[65], const __u8 *signature,
+ size_t size, const char *path)
+{
+ struct shirudo_cert cert = {};
+ char algorithm[32];
+ int rc;
+
+ rc = cert_read_file(path, &cert);
+ if (!rc)
+ rc = cert_key_algorithm(&cert, algorithm,
+ sizeof(algorithm));
+ if (!rc && strcmp(algorithm, "ML-DSA-87"))
+ rc = -EKEYREJECTED;
+ if (!rc && cms_signed_by(signature, size, &cert) != 1)
+ rc = -EKEYREJECTED;
+ if (!rc)
+ rc = verify_detached((const __u8 *)root, 64,
+ signature, size, &cert);
+ cert_free(&cert);
+ return rc;
+}
+
+static int verify_image(const char *prefix, const char *cert)
+{
+ struct shirudo_config_image_open image = {
+ .data_fd = -1, .hash_fd = -1, .signature_fd = -1,
+ };
+ __u8 signature[SHIRUDO_CONFIG_IMAGE_SIG_MAX + 1];
+ size_t size = 0;
+ char root[65];
+ ssize_t n;
+ int rc;
+
+ rc = shirudo_config_image_open(prefix, &image);
+ if (rc)
+ return rc;
+ while (size < sizeof(signature)) {
+ n = pread(image.signature_fd, signature + size,
+ sizeof(signature) - size, size);
+ if (n < 0) {
+ if (errno == EINTR)
+ continue;
+ rc = -errno;
+ goto out;
+ }
+ if (!n)
+ break;
+ size += n;
+ }
+ if (!size || size > SHIRUDO_CONFIG_IMAGE_SIG_MAX) {
+ rc = -EINVAL;
+ goto out;
+ }
+ hex_encode(image.image.root_hash, sizeof(image.image.root_hash),
+ root);
+ rc = verify_root_signature(root, signature, size, cert);
+ if (!rc)
+ rc = run_veritysetup(image.data_fd, image.hash_fd, -1,
+ &image.image);
+ if (!rc)
+ puts(root);
+out:
+ shirudo_config_image_close(&image);
+ return rc;
+}
+
+static int build_image(const char *input, const char *prefix, const char *pkey,
+ const char *cert, const __u8 salt[32])
+{
+ static const char *const suffix[] = {".img", ".verity", ".roothash",
+ ".p7s"};
+ __u8 signature[SHIRUDO_CONFIG_IMAGE_SIG_MAX];
+ struct shirudo_config_image image;
+ struct shirudo_sign_io sign = {};
+ char paths[4][PATH_MAX], root[65];
+ int fds[4] = {-1, -1, -1, -1};
+ struct stat st;
+ int in = -1, rc;
+ __u32 i;
+
+ if (shirudo_build_check_keys(pkey, cert))
+ return -EKEYREJECTED;
+ for (i = 0; i < 4; i++) {
+ rc = image_output_path(paths[i], sizeof(paths[i]), prefix,
+ suffix[i]);
+ if (rc)
+ return rc;
+ }
+ in = open(input, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK);
+ if (in < 0)
+ return -errno;
+ if (fstat(in, &st)) {
+ rc = -errno;
+ goto out;
+ }
+ if (!S_ISREG(st.st_mode) || st.st_size <= 0 ||
+ (__u64)st.st_size > SHIRUDO_CONFIG_IMAGE_MAX_BYTES ||
+ st.st_size % SHIRUDO_CONFIG_IMAGE_BLOCK_SIZE) {
+ rc = -EINVAL;
+ goto out;
+ }
+ for (i = 0; i < 4; i++) {
+ fds[i] = open(paths[i], O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC,
+ 0644);
+ if (fds[i] < 0) {
+ rc = -errno;
+ goto out;
+ }
+ }
+ rc = copy_image(in, fds[0], st.st_size);
+ if (!rc)
+ rc = format_image(fds[0], fds[1], st.st_size, salt,
+ &image);
+ if (rc)
+ goto out;
+ hex_encode(image.root_hash, sizeof(image.root_hash), root);
+ sign.insns = root;
+ sign.insns_sz = 64;
+ sign.signature = signature;
+ sign.signature_sz = sizeof(signature);
+ rc = cms_sign(&sign, pkey, cert);
+ if (!rc)
+ rc = verify_root_signature(root, signature, sign.signature_sz,
+ cert);
+ if (!rc)
+ rc = write_complete(fds[2], root, 64);
+ if (!rc)
+ rc = write_complete(fds[3], signature, sign.signature_sz);
+ for (i = 0; !rc && i < 4; i++)
+ if (fsync(fds[i]))
+ rc = -errno;
+ if (!rc)
+ puts(root);
+out:
+ if (in >= 0)
+ close(in);
+ for (i = 0; i < 4; i++) {
+ if (fds[i] < 0)
+ continue;
+ close(fds[i]);
+ if (rc)
+ unlink(paths[i]);
+ }
+ return rc;
+}
+
+int shirudo_build_image(int argc, char **argv)
+{
+ const char *pkey = SHIRUDO_SIGNING_KEY_PATH;
+ const char *cert = SHIRUDO_CERT_PATH;
+ const char *keys_dir = NULL, *salt_hex = NULL;
+ const char *input = NULL, *prefix = NULL;
+ bool explicit_key = false, explicit_cert = false;
+ char pkey_path[PATH_MAX], cert_path[PATH_MAX];
+ __u8 salt[SHIRUDO_CONFIG_IMAGE_SALT_SIZE];
+ int i, rc;
+
+ if (argc == 2 && !strcmp(argv[1], "--help")) {
+ image_usage(stdout);
+ return 0;
+ }
+ if (argc == 5 && !strcmp(argv[1], "verify") &&
+ !strcmp(argv[3], "--cert")) {
+ rc = verify_image(argv[2], argv[4]);
+ if (rc)
+ pr_err("image verify: %s", strerror(-rc));
+ return rc ? 1 : 0;
+ }
+ if (argc < 2 || strcmp(argv[1], "build")) {
+ image_usage(stderr);
+ return 2;
+ }
+ for (i = 2; i < argc; i++) {
+ const char *arg = argv[i];
+
+ if (!strcmp(arg, "--help")) {
+ image_usage(stdout);
+ return 0;
+ }
+ if (!strcmp(arg, "-o") && i + 1 < argc) {
+ prefix = argv[++i];
+ } else if (!strcmp(arg, "--keys-dir") && i + 1 < argc) {
+ keys_dir = argv[++i];
+ } else if (!strcmp(arg, "--key") && i + 1 < argc) {
+ pkey = argv[++i];
+ explicit_key = true;
+ } else if (!strcmp(arg, "--cert") && i + 1 < argc) {
+ cert = argv[++i];
+ explicit_cert = true;
+ } else if (!strcmp(arg, "--salt") && i + 1 < argc) {
+ salt_hex = argv[++i];
+ } else if (!strcmp(arg, "--kind") && i + 1 < argc) {
+ arg = argv[++i];
+ if (strcmp(arg, "config") && strcmp(arg, "runtime"))
+ return 2;
+ } else if (arg[0] != '-' && !input) {
+ input = arg;
+ } else {
+ image_usage(stderr);
+ return 2;
+ }
+ }
+ if (!input || !prefix || !*prefix)
+ return 2;
+ keys_dir = keys_dir_resolve(keys_dir);
+ if (keys_dir) {
+ rc = key_paths(keys_dir, pkey_path, sizeof(pkey_path),
+ cert_path, sizeof(cert_path));
+ if (rc)
+ return 2;
+ if (!explicit_key)
+ pkey = pkey_path;
+ if (!explicit_cert)
+ cert = cert_path;
+ }
+ if (salt_hex) {
+ if (strlen(salt_hex) != 64 ||
+ hex_decode(salt_hex, salt, sizeof(salt)))
+ return 2;
+ } else if (RAND_bytes(salt, sizeof(salt)) != 1) {
+ return 1;
+ }
+ rc = build_image(input, prefix, pkey, cert, salt);
+ if (rc)
+ pr_err("image build: %s", strerror(-rc));
+ return rc ? 1 : 0;
+}
diff --git a/tools/shirudo-build/image.h b/tools/shirudo-build/image.h
new file mode 100644
index 00000000..41f3b8fa
--- /dev/null
+++ b/tools/shirudo-build/image.h
@@ -0,0 +1,9 @@
+/* SPDX-License-Identifier: BSD-2-Clause */
+/* Copyright (c) 2026 Authors of shirudo */
+
+#ifndef SHIRUDO_BUILD_IMAGE_H
+#define SHIRUDO_BUILD_IMAGE_H
+
+int shirudo_build_image(int argc, char **argv);
+
+#endif /* SHIRUDO_BUILD_IMAGE_H */
diff --git a/tools/shirudo-build/shirudo-build.c b/tools/shirudo-build/shirudo-build.c
index 127802dd..5b4dbb00 100644
--- a/tools/shirudo-build/shirudo-build.c
+++ b/tools/shirudo-build/shirudo-build.c
@@ -21,6 +21,7 @@
#include "harden.h"
#include "log.h"
#include "hex.h"
+#include "image.h"
#include "malloc.h"
#include "package.h"
#include "paths.h"
@@ -48,6 +49,7 @@ static void usage(FILE *fp)
" [--keys-dir <dir>]\n"
" [--key <signing_key.pem>] [--cert <cert.der>]\n"
"\n"
+ " shirudo-build image build <filesystem.img> -o <prefix> ...\n"
" shirudo-build bpm <build|push|tree append> ...\n"
" shirudo-build keys vouch <cert.der> [-o <file>] ...\n"
"\n"
@@ -208,6 +210,8 @@ int main(int argc, char **argv)
log_init();
harden_self();
+ if (argc >= 2 && strcmp(argv[1], "image") == 0)
+ return shirudo_build_image(argc - 1, argv + 1);
if (argc >= 2 && strcmp(argv[1], "bpm") == 0)
return shirudo_build_bpm(argc - 1, argv + 1);
if (argc >= 3 && strcmp(argv[1], "keys") == 0 &&
diff --git a/util/config_image.c b/util/config_image.c
new file mode 100644
index 00000000..eb88c408
--- /dev/null
+++ b/util/config_image.c
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include <shirudo/misc.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "config_image.h"
+#include "hex.h"
+
+#define IMAGE_DIGESTS_PER_BLOCK (SHIRUDO_CONFIG_IMAGE_BLOCK_SIZE / 32)
+
+static __u32 get_le32(const __u8 *p)
+{
+ return (__u32)p[0] | (__u32)p[1] << 8 |
+ (__u32)p[2] << 16 | (__u32)p[3] << 24;
+}
+
+static __u64 get_le64(const __u8 *p)
+{
+ return (__u64)get_le32(p) | (__u64)get_le32(p + 4) << 32;
+}
+
+static int hash_blocks(__u64 data_blocks, __u64 *out)
+{
+ __u64 total = 1;
+
+ if (!data_blocks || data_blocks > SHIRUDO_CONFIG_IMAGE_MAX_BYTES /
+ SHIRUDO_CONFIG_IMAGE_BLOCK_SIZE)
+ return -EFBIG;
+ while (data_blocks > 1) {
+ data_blocks = (data_blocks + IMAGE_DIGESTS_PER_BLOCK - 1) /
+ IMAGE_DIGESTS_PER_BLOCK;
+ total += data_blocks;
+ }
+ *out = total;
+ return 0;
+}
+
+static int regular_size(int fd, __u64 *size)
+{
+ struct stat st;
+
+ *size = 0;
+ if (fstat(fd, &st))
+ return -errno;
+ if (!S_ISREG(st.st_mode) || st.st_size < 0)
+ return -EINVAL;
+ *size = st.st_size;
+ return 0;
+}
+
+static int read_at_start(int fd, void *buffer, size_t size)
+{
+ size_t done = 0;
+ ssize_t n;
+
+ while (done < size) {
+ n = pread(fd, (__u8 *)buffer + done, size - done, done);
+ if (n < 0) {
+ if (errno == EINTR)
+ continue;
+ return -errno;
+ }
+ if (!n)
+ return -EIO;
+ done += n;
+ }
+ return 0;
+}
+
+/* Standard veritysetup superblock fields, in little-endian disk order. */
+int shirudo_config_image_read_header(int hash_fd,
+ struct shirudo_config_image *out)
+{
+ static const __u8 magic[8] = "verity";
+ static const char algorithm[32] = "sha256";
+ struct shirudo_config_image image = {};
+ __u8 header[512];
+ int rc;
+
+ if (!out)
+ return -EINVAL;
+ rc = read_at_start(hash_fd, header, sizeof(header));
+ if (rc)
+ return rc;
+ if (memcmp(header, magic, sizeof(magic)) ||
+ get_le32(header + 8) != 1 || get_le32(header + 12) != 1 ||
+ memcmp(header + 32, algorithm, sizeof(algorithm)) ||
+ get_le32(header + 64) != SHIRUDO_CONFIG_IMAGE_BLOCK_SIZE ||
+ get_le32(header + 68) != SHIRUDO_CONFIG_IMAGE_BLOCK_SIZE ||
+ header[80] != SHIRUDO_CONFIG_IMAGE_SALT_SIZE || header[81])
+ return -EINVAL;
+ image.data_blocks = get_le64(header + 72);
+ rc = hash_blocks(image.data_blocks, &image.hash_blocks);
+ if (rc)
+ return rc;
+ memcpy(image.salt, header + 88, sizeof(image.salt));
+ *out = image;
+ return 0;
+}
+
+int shirudo_config_image_check_files(int data_fd, int hash_fd,
+ const struct shirudo_config_image *image)
+{
+ __u64 data_size, hash_size, blocks;
+ int rc;
+
+ if (!image)
+ return -EINVAL;
+ rc = hash_blocks(image->data_blocks, &blocks);
+ if (rc)
+ return rc;
+ if (blocks != image->hash_blocks)
+ return -EINVAL;
+ rc = regular_size(data_fd, &data_size);
+ if (!rc)
+ rc = regular_size(hash_fd, &hash_size);
+ if (rc)
+ return rc;
+ if (data_size != image->data_blocks * SHIRUDO_CONFIG_IMAGE_BLOCK_SIZE ||
+ hash_size != image->hash_blocks * SHIRUDO_CONFIG_IMAGE_BLOCK_SIZE)
+ return -EINVAL;
+ return 0;
+}
+
+static int open_part(const char *prefix, const char *suffix)
+{
+ char path[PATH_MAX];
+ int n, fd;
+
+ n = snprintf(path, sizeof(path), "%s%s", prefix, suffix);
+ if (n < 0 || (size_t)n >= sizeof(path))
+ return -ENAMETOOLONG;
+ fd = open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK);
+ return fd < 0 ? -errno : fd;
+}
+
+static int read_root(const char *prefix, __u8 root[32])
+{
+ char text[65] = {};
+ __u64 size;
+ __u32 i;
+ int fd, rc;
+
+ fd = open_part(prefix, ".roothash");
+ if (fd < 0)
+ return fd;
+ rc = regular_size(fd, &size);
+ if (!rc && size != 64)
+ rc = -EINVAL;
+ if (!rc)
+ rc = read_at_start(fd, text, 64);
+ close(fd);
+ if (rc)
+ return rc;
+ for (i = 0; i < 64; i++)
+ if (!((text[i] >= '0' && text[i] <= '9') ||
+ (text[i] >= 'a' && text[i] <= 'f')))
+ return -EINVAL;
+ return hex_decode(text, root, 32);
+}
+
+void shirudo_config_image_close(struct shirudo_config_image_open *image)
+{
+ if (!image)
+ return;
+ if (image->data_fd >= 0)
+ close(image->data_fd);
+ if (image->hash_fd >= 0)
+ close(image->hash_fd);
+ if (image->signature_fd >= 0)
+ close(image->signature_fd);
+ image->data_fd = -1;
+ image->hash_fd = -1;
+ image->signature_fd = -1;
+}
+
+static int open_image(const char *prefix, const __u8 *expected_root,
+ struct shirudo_config_image_open *out)
+{
+ struct shirudo_config_image_open image = {
+ .data_fd = -1, .hash_fd = -1, .signature_fd = -1,
+ };
+ __u64 size;
+ int rc;
+
+ if (!prefix || !*prefix || !out)
+ return -EINVAL;
+ *out = image;
+ image.data_fd = open_part(prefix, ".img");
+ if (image.data_fd < 0)
+ return image.data_fd;
+ image.hash_fd = open_part(prefix, ".verity");
+ if (image.hash_fd < 0) {
+ rc = image.hash_fd;
+ goto out;
+ }
+ rc = shirudo_config_image_read_header(image.hash_fd,
+ &image.image);
+ if (!rc)
+ rc = read_root(prefix, image.image.root_hash);
+ if (!rc)
+ rc = shirudo_config_image_check_files(image.data_fd,
+ image.hash_fd,
+ &image.image);
+ if (rc)
+ goto out;
+ if (expected_root) {
+ if (memcmp(expected_root, image.image.root_hash, 32))
+ rc = -EKEYREJECTED;
+ } else {
+ image.image.signed_root = true;
+ image.signature_fd = open_part(prefix, ".p7s");
+ rc = image.signature_fd < 0 ? image.signature_fd :
+ regular_size(image.signature_fd, &size);
+ if (!rc && (!size || size > SHIRUDO_CONFIG_IMAGE_SIG_MAX))
+ rc = -EINVAL;
+ }
+out:
+ if (rc)
+ shirudo_config_image_close(&image);
+ else
+ *out = image;
+ return rc;
+}
+
+int shirudo_config_image_open(const char *prefix,
+ struct shirudo_config_image_open *out)
+{
+ return open_image(prefix, NULL, out);
+}
+
+int shirudo_config_image_open_root(const char *prefix,
+ const __u8 expected_root[32],
+ struct shirudo_config_image_open *out)
+{
+ return expected_root ? open_image(prefix, expected_root, out) : -EINVAL;
+}
diff --git a/util/config_image.h b/util/config_image.h
new file mode 100644
index 00000000..67d4bb0b
--- /dev/null
+++ b/util/config_image.h
@@ -0,0 +1,46 @@
+/* SPDX-License-Identifier: BSD-2-Clause */
+/* Copyright (c) 2026 Authors of shirudo */
+
+#ifndef SHIRUDO_CONFIG_IMAGE_H
+#define SHIRUDO_CONFIG_IMAGE_H
+
+#include <shirudo/misc.h>
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#define SHIRUDO_CONFIG_IMAGE_BLOCK_SIZE 4096u
+#define SHIRUDO_CONFIG_IMAGE_SALT_SIZE 32u
+#define SHIRUDO_CONFIG_IMAGE_SIG_MAX 16384u
+#define SHIRUDO_CONFIG_IMAGE_MAX_BYTES (1ull << 40)
+
+struct shirudo_config_image {
+ __u64 data_blocks;
+ __u64 hash_blocks;
+ bool signed_root;
+ __u8 salt[SHIRUDO_CONFIG_IMAGE_SALT_SIZE];
+ __u8 root_hash[32];
+};
+
+struct shirudo_config_image_open {
+ struct shirudo_config_image image;
+ int data_fd;
+ int hash_fd;
+ int signature_fd;
+};
+
+/* Read the standard veritysetup superblock; no trust decision is made. */
+int shirudo_config_image_read_header(int hash_fd,
+ struct shirudo_config_image *out);
+int shirudo_config_image_check_files(int data_fd, int hash_fd,
+ const struct shirudo_config_image *image);
+/* Hold config inputs for kernel root-signature and mapped-data verification. */
+int shirudo_config_image_open(const char *prefix,
+ struct shirudo_config_image_open *out);
+int shirudo_config_image_open_root(const char *prefix,
+ const __u8 expected_root[32],
+ struct shirudo_config_image_open *out);
+void shirudo_config_image_close(struct shirudo_config_image_open *image);
+
+#endif /* SHIRUDO_CONFIG_IMAGE_H */
diff --git a/util/crypto_openssl.c b/util/crypto_openssl.c
index 600c23be..a7d45be3 100644
--- a/util/crypto_openssl.c
+++ b/util/crypto_openssl.c
@@ -264,6 +264,21 @@ int cert_key_algorithm(const struct shirudo_cert *cert,
return 0;
}
+static CMS_ContentInfo *read_cms(const __u8 *signature, size_t len)
+{
+ const __u8 *next = signature;
+ CMS_ContentInfo *cms;
+
+ if (!signature || !len || len > INT_MAX)
+ return NULL;
+ cms = d2i_CMS_ContentInfo(NULL, &next, (long)len);
+ if (cms && next != signature + len) {
+ CMS_ContentInfo_free(cms);
+ cms = NULL;
+ }
+ return cms;
+}
+
/*
* The algorithm comes from the SignerInfo, so an ML-DSA signature,
* with signedAttrs and SHA-512 or bare on OpenSSL 4, and an RSA one
@@ -273,27 +288,26 @@ int verify_detached(const __u8 *payload, size_t payload_len,
const __u8 *signature, size_t signature_len,
const struct shirudo_cert *cert)
{
- BIO *sig = NULL, *data = NULL, *out = NULL;
- CMS_ContentInfo *cms = NULL;
STACK_OF(X509) *signers = NULL;
+ BIO *data = NULL, *out = NULL;
+ CMS_ContentInfo *cms = NULL;
X509_STORE *store = NULL;
int rc = -EINVAL;
if (!payload || !signature || !cert || !cert->impl ||
payload_len > INT_MAX || signature_len > INT_MAX)
return -EINVAL;
- sig = BIO_new_mem_buf(signature, (int)signature_len);
data = BIO_new_mem_buf(payload, (int)payload_len);
out = BIO_new(BIO_s_null());
store = X509_STORE_new();
- if (!sig || !data || !out || !store ||
+ if (!data || !out || !store ||
X509_STORE_add_cert(store, cert->impl) != 1 ||
X509_STORE_set_flags(store, X509_V_FLAG_NO_CHECK_TIME) != 1)
goto done;
signers = sk_X509_new_null();
if (!signers || !sk_X509_push(signers, cert->impl))
goto done;
- cms = d2i_CMS_bio(sig, NULL);
+ cms = read_cms(signature, signature_len);
if (cms && CMS_verify(cms, signers, store, data, out,
CMS_BINARY | CMS_DETACHED) == 1)
rc = 0;
@@ -305,7 +319,6 @@ done:
X509_STORE_free(store);
BIO_free(out);
BIO_free(data);
- BIO_free(sig);
return rc;
}
@@ -314,15 +327,11 @@ int cms_signed_by(const __u8 *signature, size_t signature_len,
{
STACK_OF(CMS_SignerInfo) *sis;
CMS_ContentInfo *cms = NULL;
- BIO *sig = NULL;
int i, rc = -EINVAL;
if (!signature || !cert || !cert->impl || signature_len > INT_MAX)
return -EINVAL;
- sig = BIO_new_mem_buf(signature, (int)signature_len);
- if (!sig)
- goto done;
- cms = d2i_CMS_bio(sig, NULL);
+ cms = read_cms(signature, signature_len);
if (!cms)
goto done;
sis = CMS_get0_SignerInfos(cms);
@@ -338,7 +347,6 @@ done:
if (rc < 0)
ERR_clear_error();
CMS_ContentInfo_free(cms);
- BIO_free(sig);
return rc;
}