eBPF-based security platform
bpm: keep downloads and snapshots in memory, not in /tmp
Daniel Borkmann805943ca52a6
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex ef9bcf22..ba1a99bc 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -513,7 +513,9 @@ signed config image.- Subcommands, reference validation before network access, sourceand tree configuration lines* - ``t7002-bpm-info``- - READMEs of local and OCI packages, archive integrity+ - READMEs of local and OCI packages, archive integrity, a download+ kept in a memory file rather than in ``/tmp``, and one key+ fingerprint from a certificate, a package and a download* - ``t7003-bpm-key``- ``bpm key`` from files and OCI references, ``bpm pull``, whichreplaces no file, not even after a failed digest, and names nonediff --git a/Documentation/reference/cli/bpm.rst b/Documentation/reference/cli/bpm.rstindex 1500972a..d8cdde15 100644--- a/Documentation/reference/cli/bpm.rst+++ b/Documentation/reference/cli/bpm.rst@@ -402,7 +402,8 @@ key- ``key fingerprint`` prints the SHA-256 fingerprint of a certificate'spublic key (SPKI). The argument is a DER certificate, a ``.bee`` package- (its ``cert.der``) or an ``oci://`` package reference.+ (its ``cert.der``) or an ``oci://`` package reference. The certificate+ is read once, so ``key add`` installs the bytes it fingerprints.- ``key add`` prints the same fingerprint and installs the certificate in``/var/lib/shirudo/keys/<fingerprint>.der``. When``/var/lib/shirudo/keys/cert.der`` does not exist, it links ``cert.der``diff --git a/Documentation/reference/environment.rst b/Documentation/reference/environment.rstindex 430263ec..b8921dba 100644--- a/Documentation/reference/environment.rst+++ b/Documentation/reference/environment.rst@@ -87,8 +87,8 @@ shirudo and shirudo-build``ExecStart=`` and ``EnvironmentFile=``, so the variable has noeffect with it.* - ``TMPDIR``- - ``upatch map`` (snapshot file), ``shirudo-build bpm build``- (staging directory), the generator scripts (``mktemp -d``)+ - ``shirudo-build bpm build`` (staging directory), the generator+ scripts (``mktemp -d``)- Directory for temporary files, ``/tmp`` when unset or empty.* - ``HOME``- Registry credential lookup; ``shirudo-build bpm build`` expandingdiff --git a/Documentation/reference/files.rst b/Documentation/reference/files.rstindex f6246e76..60648053 100644--- a/Documentation/reference/files.rst+++ b/Documentation/reference/files.rst@@ -520,10 +520,12 @@ Kernel and system interfacesTemporary files----------------``bpm info`` and ``bpm key`` create ``/tmp/shirudo-bpm-*-XXXXXX``-files. ``upatch map --s3-uri`` writes a-snapshot to ``$TMPDIR/shirudo-map-snapshot.XXXXXX`` (``/tmp`` when-``TMPDIR`` is unset) with mode ``0600``.+The target commands create none. ``bpm info`` and ``bpm key`` keep a+downloaded package in a memory file, ``memfd:shirudo-bpm-package``, and+``upatch map --s3-uri`` its snapshot in ``memfd:shirudo-map-snapshot``:+a file of ``/tmp`` or of ``TMPDIR``, which root chooses, could be+created in a sealed directory bound there, with the label and content+from a registry.Related-------diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rstindex f9827160..dc309693 100644--- a/Documentation/security/threat-model.rst+++ b/Documentation/security/threat-model.rst@@ -1723,7 +1723,10 @@ R22 Labeled inodes are interchangeableits own, root can bind one labeled inode over another sealed pathfor a shirudo command it runs there. U9 is one consequence; othersare a hidden eventlog, which makes measuring commands fail, and- package or tree state read from the wrong file. This is a reading of+ package or tree state read from the wrong file. What root can bind is+ what shirudo labeled: no target command writes a temporary file,+ which a sealed directory bound over ``/tmp`` would have labeled with+ content from a registry (``t7002``). This is a reading ofthe code and is not reproduced. A bind mount over the state root in``init``'s namespace, an idmapped one among them, was reproduced:every command refuses the state as foreign from then on.diff --git a/builtin-bpm.c b/builtin-bpm.cindex 776cf2fb..f897963e 100644--- a/builtin-bpm.c+++ b/builtin-bpm.c@@ -17,6 +17,7 @@#include <stdlib.h>#include <string.h>#include <sys/file.h>+#include <sys/mman.h>#include <sys/stat.h>#include <sys/types.h>#include <unistd.h>@@ -65,6 +66,7 @@ struct bpm_source {};static int sha256_file_hex(const char *path, char *hex, size_t hex_sz);+static int sha256_fd_hex(int fd, char *hex, size_t hex_sz);static int remove_tree(const char *path);static int prepare_direct_install(const char *raw, struct bpm_source *source,@@ -145,7 +147,33 @@ static bool bee_title_ok(const char *title)* opened as output root may ask for: never a sealed file nor one* reached through a link.*/-static int download_package(const char *raw, const char *destination, int fd)+/* The layer's title, else <package>-<tag>.bee. */+static int pull_filename(const char *repository, const char *tag,+ const char *package_name, const char *title,+ char *filename, size_t cap)+{+ const char *base = strrchr(repository, '/');++ if (bee_title_ok(title)) {+ bpm_copy_string(filename, cap, title);+ return 0;+ }+ base = base ? base + 1 : repository;+ if (package_name[0])+ base = package_name;+ if (!bpm_package_name_ok(base))+ return -EINVAL;+ if (strsprintf(filename, cap, "%s-%s.bee", base, tag) < 0)+ return -ENAMETOOLONG;+ return 0;+}++/*+ * Download the package raw names into fd, or with fd -1 into a file of+ * the working directory, and check what was written there, read back+ * from the descriptor that wrote it.+ */+static int download_package(const char *raw, int fd){struct bpm_oci_client c __cleanup(bpm_oci_client_clear) = {};struct bpm_descriptor layers[8];@@ -183,29 +211,13 @@ static int download_package(const char *raw, const char *destination, int fd)/* A cut title would name another file; fall back to the package name. */if (bpm_trim(layers[i].title, title, sizeof(title)))title[0] = '\0';- if (destination) {- bpm_copy_string(filename, sizeof(filename), destination);- } else if (bee_title_ok(title)) {- bpm_copy_string(filename, sizeof(filename), title);- } else {- const char *base = strrchr(repository, '/');-- base = base ? base + 1 : repository;- if (package_name[0])- base = package_name;- if (!bpm_package_name_ok(base)) {- ret = -EINVAL;- goto out;- }- if (strsprintf(filename, sizeof(filename), "%s-%s.bee",- base, tag) < 0) {- ret = -ENAMETOOLONG;+ if (fd < 0) {+ ret = pull_filename(repository, tag, package_name, title,+ filename, sizeof(filename));+ if (ret)goto out;- }- }- if (!destination) {out = seal_output_open(filename,- O_WRONLY | O_CREAT | O_EXCL,+ O_RDWR | O_CREAT | O_EXCL,0644);if (out < 0) {ret = out;@@ -214,18 +226,18 @@ static int download_package(const char *raw, const char *destination, int fd)}ret = bpm_oci_get_file(&c, url, BPM_PACKAGE_MEDIA, out,layers[i].size);- if (!destination)- close(out);- if (!ret && (sha256_file_hex(filename, digest, sizeof(digest)) ||+ if (!ret && (sha256_fd_hex(out, digest, sizeof(digest)) ||!bpm_digest_matches(layers[i].digest, digest)))ret = -EKEYREJECTED;if (!ret && layers[i].size >= 0) {struct stat st;- if (stat(filename, &st) || st.st_size != layers[i].size)+ if (fstat(out, &st) || st.st_size != layers[i].size)ret = -EKEYREJECTED;}- if (ret && !destination)+ if (fd < 0)+ close(out);+ if (ret && fd < 0)unlink(filename);goto out;}@@ -237,7 +249,7 @@ out:static int pull_package(const char *raw){- return download_package(raw, NULL, -1);+ return download_package(raw, -1);}static int copy_file_ex(const char *src, const char *dst, mode_t mode,@@ -478,55 +490,79 @@ static int cache_path(const char *source, char *out, size_t sz)return 0;}-static int sha256_file_hex(const char *path, char *hex, size_t hex_sz)+/* The digest of fd's bytes from its start, whatever its offset. */+static int sha256_fd_hex(int fd, char *hex, size_t hex_sz){- struct sha256_ctx ctx;__u8 digest[CRYPTO_SHA256_LEN];+ struct sha256_ctx ctx;__u8 buf[65536];+ off_t at = 0;ssize_t nr;- int fd, ret = -EIO;+ int ret = -EIO;if (hex_sz < 65 || sha256_init(&ctx) != 0)return -EINVAL;- fd = open(path, O_RDONLY | O_CLOEXEC);- if (fd < 0) {- sha256_free(&ctx);- return -errno;- }- while ((nr = read(fd, buf, sizeof(buf))) > 0) {+ while ((nr = pread(fd, buf, sizeof(buf), at)) > 0) {if (sha256_update(&ctx, buf, (size_t)nr) != 0)goto done;+ at += nr;}if (nr < 0 || sha256_final(&ctx, digest) != 0)goto done;hex_encode(digest, sizeof(digest), hex);ret = 0;done:- close(fd);sha256_free(&ctx);return ret;}+static int sha256_file_hex(const char *path, char *hex, size_t hex_sz)+{+ int fd, ret;++ fd = open(path, O_RDONLY | O_CLOEXEC);+ if (fd < 0)+ return -errno;+ ret = sha256_fd_hex(fd, hex, hex_sz);+ close(fd);+ return ret;+}++/*+ * A package the operator names, open for reading: the local file, or+ * the download in memory. Never a file of /tmp, which root can bind to a+ * sealed directory for shirudo to create a labeled file in.+ */+static int package_source_open(const char *source)+{+ int fd, ret;++ if (strncmp(source, "oci://", 6)) {+ fd = open(source, O_RDONLY | O_CLOEXEC);+ return fd < 0 ? -errno : fd;+ }+ fd = memfd_create("shirudo-bpm-package", MFD_CLOEXEC);+ if (fd < 0)+ return -errno;+ ret = download_package(source, fd);+ if (ret) {+ close(fd);+ return ret;+ }+ return fd;+}+static int print_package_readme(const char *source){- char temporary[] = "/tmp/shirudo-bpm-info-XXXXXX";size_t beefile_len = 0, readme_len = 0;__u8 *beefile = NULL, *readme = NULL;- const char *archive = source;char package_dir[101];int fd, ret;- if (!strncmp(source, "oci://", 6)) {- fd = mkstemp(temporary);- if (fd < 0)- return -errno;- archive = temporary;- ret = download_package(source, archive, fd);- close(fd);- if (ret)- goto out;- }- ret = bpm_pkg_read_member_in(archive, "Beefile", NULL, package_dir,+ fd = package_source_open(source);+ if (fd < 0)+ return fd;+ ret = bpm_pkg_read_member_fd(fd, "Beefile", NULL, package_dir,sizeof(package_dir), &beefile, &beefile_len,4u * 1024u * 1024u);if (ret) {@@ -534,7 +570,7 @@ static int print_package_readme(const char *source)pr_err("bpm info: package %s does not include Beefile", source);goto out;}- ret = bpm_pkg_read_member_in(archive, "README.md", package_dir, NULL, 0,+ ret = bpm_pkg_read_member_fd(fd, "README.md", package_dir, NULL, 0,&readme, &readme_len, 4u * 1024u * 1024u);if (ret) {if (ret == -ENOENT)@@ -546,8 +582,7 @@ static int print_package_readme(const char *source)out:xfree(beefile, beefile_len + 1);xfree(readme, readme_len + 1);- if (archive == temporary)- unlink(temporary);+ close(fd);return ret;}@@ -603,43 +638,23 @@ static int print_upatch_member(void *ctx, const char *member, char type)return 0;}-static int bpm_info_archive(const char *source, char temporary[])-{- int fd, ret;-- if (strncmp(source, "oci://", 6))- return 0;- fd = mkstemp(temporary);- if (fd < 0)- return -errno;- ret = download_package(source, temporary, fd);- close(fd);- if (ret)- unlink(temporary);- return ret;-}-static int print_package_upatches(const char *source, bool all){- char temporary[] = "/tmp/shirudo-bpm-upatches-XXXXXX";+ struct bpm_upatches_ctx ctx = { .all = all };size_t beefile_len = 0;__u8 *beefile = NULL;- const char *archive = source;char package_dir[101];- struct bpm_upatches_ctx ctx = { .all = all };- int ret = 0;+ int fd, ret;- ret = bpm_info_archive(source, temporary);- if (ret)- return ret;- if (!strncmp(source, "oci://", 6))- archive = temporary;- ret = bpm_pkg_read_member_in(archive, "Beefile", NULL, package_dir,+ fd = package_source_open(source);+ if (fd < 0)+ return fd;+ ret = bpm_pkg_read_member_fd(fd, "Beefile", NULL, package_dir,sizeof(package_dir), &beefile, &beefile_len,4u * 1024u * 1024u);if (!ret)- ret = bpm_pkg_visit_members(archive, package_dir,- print_upatch_member, &ctx);+ ret = bpm_pkg_visit_members_fd(fd, package_dir,+ print_upatch_member, &ctx);if (!ret && ctx.len)ret = write_complete(STDOUT_FILENO, ctx.list, ctx.len);if (ret == -ENOENT)@@ -647,33 +662,28 @@ static int print_package_upatches(const char *source, bool all)source);xfree(beefile, beefile_len + 1);xfree(ctx.list, ctx.cap);- if (archive == temporary)- unlink(temporary);+ close(fd);return ret;}static int print_package_upatch_data(const char *source, const char *member,bool json){- char temporary[] = "/tmp/shirudo-bpm-data-XXXXXX";size_t beefile_len = 0, upatch_len = 0;__u8 *beefile = NULL, *bytes = NULL;- const char *archive = source;char package_dir[101];struct upatch u = {};- int ret;+ int fd, ret;if (!bpm_archive_rel_ok(member) || strncmp(member, "upatches/", 9) ||strchr(member + 9, '/') ||bpm_upatch_member(member + 9, strlen(member + 9)) ==BPM_UPATCH_OTHER)return -EINVAL;- ret = bpm_info_archive(source, temporary);- if (ret)- return ret;- if (!strncmp(source, "oci://", 6))- archive = temporary;- ret = bpm_pkg_read_member_in(archive, "Beefile", NULL, package_dir,+ fd = package_source_open(source);+ if (fd < 0)+ return fd;+ ret = bpm_pkg_read_member_fd(fd, "Beefile", NULL, package_dir,sizeof(package_dir), &beefile, &beefile_len,4u * 1024u * 1024u);if (ret) {@@ -682,7 +692,7 @@ static int print_package_upatch_data(const char *source, const char *member,source);goto out;}- ret = bpm_pkg_read_member_in(archive, member, package_dir, NULL, 0,+ ret = bpm_pkg_read_member_fd(fd, member, package_dir, NULL, 0,&bytes, &upatch_len,UPATCH_FILE_MAX);if (ret) {@@ -712,18 +722,18 @@ out:upatch_close(&u);xfree(beefile, beefile_len + 1);xfree(bytes, upatch_len + 1);- if (archive == temporary)- unlink(temporary);+ close(fd);return ret;}-static int cert_matches_active(const char *path)+/* 0 when the certificate has the public key of the active cert.der. */+static int cert_matches_active(const __u8 *der, size_t len){struct cert a = {}, b = {};__u8 da[CRYPTO_SHA256_LEN], db[CRYPTO_SHA256_LEN];int ret = -EINVAL;- if (!cert_read_file(path, &a) &&+ if (!cert_read_memory(der, len, &a) &&!cert_read_file(CERT_PATH, &b) &&!cert_pubkey_digest(&a, da) &&!cert_pubkey_digest(&b, db) &&@@ -734,13 +744,27 @@ static int cert_matches_active(const char *path)return ret;}-static int key_file_fingerprint(const char *path, char hex[65])+static int cert_file_matches_active(const char *path)+{+ size_t len = 0;+ __u8 *der;+ int ret;++ ret = keys_read_der(path, &der, &len);+ if (ret)+ return ret;+ ret = cert_matches_active(der, len);+ xfree(der, len);+ return ret;+}++static int key_fingerprint(const __u8 *der, size_t len, char hex[65]){- struct cert cert = {};__u8 digest[CRYPTO_SHA256_LEN];+ struct cert cert = {};int ret;- ret = cert_read_file(path, &cert);+ ret = cert_read_memory(der, len, &cert);if (!ret)ret = cert_pubkey_digest(&cert, digest);cert_free(&cert);@@ -750,14 +774,45 @@ static int key_file_fingerprint(const char *path, char hex[65])return 0;}-static int install_key_file(const char *src)+static int key_file_fingerprint(const char *path, char hex[65])+{+ size_t len = 0;+ __u8 *der;+ int ret;++ ret = keys_read_der(path, &der, &len);+ if (ret)+ return ret;+ ret = key_fingerprint(der, len, hex);+ xfree(der, len);+ return ret;+}++static int write_key(const char *dst, const __u8 *der, size_t len)+{+ int fd, ret;++ fd = seal_open(dst, O_WRONLY | O_CREAT | O_EXCL, 0644);+ if (fd < 0)+ return fd;+ ret = write_complete(fd, der, len);+ if (!ret && fsync(fd))+ ret = -errno;+ if (close(fd) && !ret)+ ret = -errno;+ if (ret)+ unlink(dst);+ return ret;+}++static int install_key(const __u8 *der, size_t len){char hex[65], dst[PATH_MAX];bool active, made = false;struct stat st;int ret;- ret = key_file_fingerprint(src, hex);+ ret = key_fingerprint(der, len, hex);if (ret)return ret;ret = seal_mkdir_p(KEYS_DIR, 0700);@@ -766,7 +821,7 @@ static int install_key_file(const char *src)active = lstat(CERT_PATH, &st) == 0;if (!active && errno != ENOENT)return -errno;- if (active && cert_matches_active(src))+ if (active && cert_matches_active(der, len))return -EPERM;if (strsprintf(dst, sizeof(dst), "%s/%s.der", KEYS_DIR,hex) < 0)@@ -780,7 +835,7 @@ static int install_key_file(const char *src)} else {if (errno != ENOENT)return -errno;- ret = copy_file_ex(src, dst, 0644, true);+ ret = write_key(dst, der, len);if (ret)return ret;made = true;@@ -792,7 +847,7 @@ static int install_key_file(const char *src)ret = -errno;goto undo;}- ret = cert_matches_active(src) ? -EPERM : 0;+ ret = cert_matches_active(der, len) ? -EPERM : 0;goto undo;}ret = seal_inherit_path(CERT_PATH);@@ -802,58 +857,33 @@ undo:return ret;}-static int extract_package_cert(const char *archive, char *out, size_t out_sz)+/*+ * The DER certificate a key command takes, read once so that the key+ * installed is the one fingerprinted: the file named, or the cert.der of+ * a package, a download read in memory. *cap is what xfree() takes.+ */+static int key_source_read(const char *source, __u8 **der, size_t *len,+ size_t *cap){- char tmp[] = "/tmp/shirudo-bpm-cert-XXXXXX";- __u8 *body = NULL;- size_t len = 0;+ size_t n = strlen(source);int fd, ret;- ret = bpm_pkg_read_member(archive, "cert.der", &body, &len, 1024 * 1024);- if (ret)+ if (strncmp(source, "oci://", 6) &&+ !name_has_suffix(source, n, ".bee")) {+ ret = keys_read_der(source, der, len);+ *cap = *len;return ret;- if (sizeof(tmp) > out_sz) {- xfree(body, len + 1);- return -ENAMETOOLONG;- }- fd = mkstemp(tmp);- if (fd < 0) {- xfree(body, len + 1);- return -errno;}- ret = write_complete(fd, body, len);- if (close(fd) && !ret)- ret = -errno;- xfree(body, len + 1);- if (ret)- unlink(tmp);- else- bpm_copy_string(out, out_sz, tmp);+ fd = package_source_open(source);+ if (fd < 0)+ return fd;+ ret = bpm_pkg_read_member_fd(fd, "cert.der", NULL, NULL, 0, der, len,+ KEYS_DER_MAX);+ close(fd);+ *cap = *len + 1;return ret;}-static int key_source_file(const char *source, char *temp, size_t temp_sz)-{- char archive[] = "/tmp/shirudo-bpm-key-XXXXXX";- size_t len = strlen(source);- int fd, ret;-- if (!strncmp(source, "oci://", 6)) {- fd = mkstemp(archive);- if (fd < 0)- return -errno;- ret = download_package(source, archive, fd);- close(fd);- if (!ret)- ret = extract_package_cert(archive, temp, temp_sz);- unlink(archive);- return ret;- }- if (name_has_suffix(source, len, ".bee"))- return extract_package_cert(source, temp, temp_sz);- return 0;-}-static int key_fingerprint_compare(const void *a, const void *b){return strcmp(*(char * const *)a, *(char * const *)b);@@ -1242,7 +1272,7 @@ static int package_install(const struct bpm_source *s, const struct bpm_index_enret = -ENAMETOOLONG;goto out;}- if (cert_matches_active(cert)) {+ if (cert_file_matches_active(cert)) {ret = -EKEYREJECTED;goto out;}@@ -2782,8 +2812,10 @@ static const struct help bpm_key_help = {static int cmd_bpm_key(int argc, const char **argv){- char temp[PATH_MAX] = {}, hex[65];- const char *sub, *src;+ size_t len = 0, cap = 0;+ const char *sub;+ __u8 *der = NULL;+ char hex[65];int ret;if (argc < 2 || is_help(argv[1])) {@@ -2820,19 +2852,15 @@ static int cmd_bpm_key(int argc, const char **argv)}if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK)return bpm_fail("initialize curl", -EIO);- src = argv[2];- ret = key_source_file(src, temp, sizeof(temp));+ ret = key_source_read(argv[2], &der, &len, &cap);if (!ret) {- if (temp[0])- src = temp;- ret = key_file_fingerprint(src, hex);+ ret = key_fingerprint(der, len, hex);if (!ret && !strcmp(sub, "add"))- ret = install_key_file(src);+ ret = install_key(der, len);if (!ret)puts(hex);+ xfree(der, cap);}- if (temp[0])- unlink(temp);return bpm_finish(-1, ret, !strcmp(sub, "add") ?"key add" : "key fingerprint");}diff --git a/testing/coccinelle/fd_leak.cocci b/testing/coccinelle/fd_leak.cocciindex 7c8562ca..3e3c63f7 100644--- a/testing/coccinelle/fd_leak.cocci+++ b/testing/coccinelle/fd_leak.cocci@@ -2,10 +2,11 @@// Copyright (c) 2026 Authors of shirudo//// A descriptor that was opened is closed, returned, stored or handed to-// what closes it (fdopen(), fdopendir(), a BIO with BIO_CLOSE) on every-// path out of the function once the open succeeded. A leak on an error-// path goes unnoticed in a one-shot command until a loop or a retry-// runs out of descriptors, and keeps open what it should not.+// what closes it (fdopen(), fdopendir(), gzdopen(), a BIO with+// BIO_CLOSE) on every path out of the function once the open succeeded.+// A leak on an error path goes unnoticed in a one-shot command until a+// loop or a retry runs out of descriptors, and keeps open what it should+// not.virtual report@@ -36,6 +37,7 @@ if (\(fd < 0\|fd == -1\)) Swhen != if (fd >= 0) S1when != fdopen(fd, ...)when != fdopendir(fd)+ when != gzdopen(fd, ...)when != BIO_new_fd(fd, BIO_CLOSE)when != \(_exit\|exit\|abort\)(...)(@@ -68,6 +70,7 @@ if (\(fd < 0\|fd == -1\)) Swhen != if (fd >= 0) S1when != fdopen(fd, ...)when != fdopendir(fd)+ when != gzdopen(fd, ...)when != BIO_new_fd(fd, BIO_CLOSE)when != \(_exit\|exit\|abort\)(...)(diff --git a/testing/helper/test-bpm-info.py b/testing/helper/test-bpm-info.pyindex 2dcf9669..99b7401f 100644--- a/testing/helper/test-bpm-info.py+++ b/testing/helper/test-bpm-info.py@@ -38,21 +38,27 @@ def package(readme=README):return package_bytes(entries)-class InfoTests(unittest.TestCase):+class BpmTestCase(unittest.TestCase):def setUp(self):self.work = tempfile.TemporaryDirectory(prefix="shirudo-bpm-info-test-")self.root = Path(self.work.name)self.addCleanup(self.work.cleanup)- def run_bpm(self, *args):+ def env(self):env = {**os.environ, "BPM_OCI_SCHEME": "http","REGISTRY_AUTH_FILE": str(self.root / "absent-auth.json"),"NO_PROXY": "127.0.0.1", "no_proxy": "127.0.0.1"}env.pop("BPM_OCI_CA_FILE", None)env.pop("BPM_OCI_USERNAME", None)env.pop("BPM_OCI_PASSWORD", None)+ return env++ def run_bpm(self, *args):return subprocess.run([SHIRUDO, "bpm", *args], cwd=self.root,- capture_output=True, env=env)+ capture_output=True, env=self.env())+++class InfoTests(BpmTestCase):def run_info(self, *args):return self.run_bpm("info", *args)@@ -254,5 +260,108 @@ class InfoTests(unittest.TestCase):self.assertEqual(list(self.root.iterdir()), [])+class Registry:+ """Serves one package blob; with hold set, stops halfway until released."""++ def __init__(self, blob, hold=False):+ self.digest = "sha256:" + hashlib.sha256(blob).hexdigest()+ self.halfway = threading.Event()+ self.release = threading.Event()+ manifest = json.dumps({+ "schemaVersion": 2,+ "layers": [{+ "mediaType": "application/vnd.shirudo.bpm.package.v1+gzip",+ "digest": self.digest, "size": len(blob),+ }],+ }).encode()+ registry = self++ class Handler(http.server.BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_GET(self):+ if self.path == "/v2/test/example/manifests/1.0":+ payload = manifest+ elif self.path == "/v2/test/example/blobs/" + registry.digest:+ payload = blob+ else:+ self.send_error(404)+ return+ self.send_response(200)+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ if payload is blob and hold:+ self.wfile.write(payload[:len(payload) // 2])+ self.wfile.flush()+ registry.halfway.set()+ registry.release.wait(30)+ payload = payload[len(payload) // 2:]+ self.wfile.write(payload)++ self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ self.thread = threading.Thread(target=self.server.serve_forever,+ daemon=True)+ self.thread.start()+ self.reference = f"oci://127.0.0.1:{self.server.server_port}/test/example:1.0"++ def close(self):+ self.release.set()+ self.server.shutdown()+ self.thread.join()+ self.server.server_close()+++class MemoryTests(BpmTestCase):+ """A download bpm reads is kept in memory, never in a file of /tmp."""++ def test_oci_download_stays_in_memory(self):+ blob = package(readme=README + b"x" * 300000)+ registry = Registry(blob, hold=True)+ self.addCleanup(registry.close)+ proc = subprocess.Popen([SHIRUDO, "bpm", "info", registry.reference],+ cwd=self.root, env=self.env(),+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ self.assertTrue(registry.halfway.wait(30))+ links = []+ for fd in os.listdir(f"/proc/{proc.pid}/fd"):+ try:+ links.append(os.readlink(f"/proc/{proc.pid}/fd/{fd}"))+ except OSError:+ pass+ registry.release.set()+ out, err = proc.communicate(timeout=60)+ self.assertEqual(proc.returncode, 0, err)+ self.assertTrue(out.startswith(README), out[:80])+ self.assertTrue(any(link.startswith("/memfd:shirudo-bpm-package")+ for link in links), links)+ self.assertFalse([link for link in links if link.startswith("/tmp/")],+ links)++ def test_key_fingerprint_of_file_package_and_download(self):+ key, cert = self.root / "key.pem", self.root / "cert.der"+ made = subprocess.run(+ ["openssl", "req", "-x509", "-newkey", "ec",+ "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes",+ "-keyout", str(key), "-outform", "DER", "-out", str(cert),+ "-days", "1", "-subj", "/CN=bpm-info"],+ capture_output=True)+ if made.returncode:+ self.skipTest("openssl cannot make a certificate")+ bee = self.root / "example.bee"+ bee.write_bytes(package_bytes([+ ("example-1.0/Beefile", b'[package]\nname = "example"\n'),+ ("example-1.0/cert.der", cert.read_bytes())]))+ registry = Registry(bee.read_bytes())+ self.addCleanup(registry.close)+ prints = [self.run_bpm("key", "fingerprint", source)+ for source in (str(cert), str(bee), registry.reference)]+ for result in prints:+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual(len(prints[0].stdout.strip()), 64)+ self.assertEqual({result.stdout for result in prints},+ {prints[0].stdout})++if __name__ == "__main__":unittest.main()diff --git a/util/bpm_package.c b/util/bpm_package.cindex 35c84ba0..0bed9db1 100644--- a/util/bpm_package.c+++ b/util/bpm_package.c@@ -382,12 +382,31 @@ static bool package_member_name_ok(const char *name, const char *member)bpm_archive_rel_ok(member) && !strcmp(slash + 1, member);}-int bpm_pkg_read_member_in(const char *archive, const char *member,- const char *package_dir, char *found_dir,- size_t found_dir_sz, __u8 **out,- size_t *out_len, size_t max)+/* A gzip stream from the start of fd, on a descriptor of its own. */+static gzFile package_gzdopen(int fd)+{+ gzFile gz;+ int copy;++ if (lseek(fd, 0, SEEK_SET) < 0)+ return NULL;+ copy = fcntl(fd, F_DUPFD_CLOEXEC, 0);+ if (copy < 0)+ return NULL;+ gz = gzdopen(copy, "rb");+ if (!gz) {+ close(copy);+ errno = ENOMEM;+ }+ return gz;+}++/* Takes gz over, and its open's errno when it is NULL. */+static int read_member_gz(gzFile gz, const char *member,+ const char *package_dir, char *found_dir,+ size_t found_dir_sz, __u8 **out,+ size_t *out_len, size_t max){- gzFile gz = gzopen(archive, "rb");int ret = -ENOENT;__u8 h[512];@@ -502,6 +521,24 @@ done:return ret;}+int bpm_pkg_read_member_in(const char *archive, const char *member,+ const char *package_dir, char *found_dir,+ size_t found_dir_sz, __u8 **out,+ size_t *out_len, size_t max)+{+ return read_member_gz(gzopen(archive, "rb"), member, package_dir,+ found_dir, found_dir_sz, out, out_len, max);+}++int bpm_pkg_read_member_fd(int fd, const char *member,+ const char *package_dir, char *found_dir,+ size_t found_dir_sz, __u8 **out,+ size_t *out_len, size_t max)+{+ return read_member_gz(package_gzdopen(fd), member, package_dir,+ found_dir, found_dir_sz, out, out_len, max);+}+int bpm_pkg_read_member(const char *archive, const char *member,__u8 **out, size_t *out_len, size_t max){@@ -509,10 +546,10 @@ int bpm_pkg_read_member(const char *archive, const char *member,out, out_len, max);}-int bpm_pkg_visit_members(const char *archive, const char *package_dir,- bpm_pkg_member_fn visit, void *ctx)+/* Takes gz over, and its open's errno when it is NULL. */+static int visit_members_gz(gzFile gz, const char *package_dir,+ bpm_pkg_member_fn visit, void *ctx){- gzFile gz = gzopen(archive, "rb");char root[256] = {};__u8 h[512];int ret = 0;@@ -635,6 +672,18 @@ done:return ret;}+int bpm_pkg_visit_members(const char *archive, const char *package_dir,+ bpm_pkg_member_fn visit, void *ctx)+{+ return visit_members_gz(gzopen(archive, "rb"), package_dir, visit, ctx);+}++int bpm_pkg_visit_members_fd(int fd, const char *package_dir,+ bpm_pkg_member_fn visit, void *ctx)+{+ return visit_members_gz(package_gzdopen(fd), package_dir, visit, ctx);+}+static X509 *read_x509_memory(const __u8 *body, size_t len){BIO *b;diff --git a/util/bpm_package.h b/util/bpm_package.hindex 64ea379a..bb014801 100644--- a/util/bpm_package.h+++ b/util/bpm_package.h@@ -72,9 +72,15 @@ int bpm_upatch_pair(const char *name, size_t len, char *out, size_t cap);typedef int (*bpm_pkg_member_fn)(void *ctx, const char *member, char type);-/* Visit validated package-relative ustar members without extracting them. */+/*+ * Visit validated package-relative ustar members without extracting them.+ * The _fd variants read the archive from the start of fd, which they+ * leave open.+ */int bpm_pkg_visit_members(const char *archive, const char *package_dir,bpm_pkg_member_fn visit, void *ctx);+int bpm_pkg_visit_members_fd(int fd, const char *package_dir,+ bpm_pkg_member_fn visit, void *ctx);/** Read one member of a gzip'd ustar .bee into an xmalloc'd buffer of@@ -86,6 +92,10 @@ int bpm_pkg_read_member_in(const char *archive, const char *member,const char *package_dir, char *found_dir,size_t found_dir_sz, __u8 **out,size_t *out_len, size_t max);+int bpm_pkg_read_member_fd(int fd, const char *member,+ const char *package_dir, char *found_dir,+ size_t found_dir_sz, __u8 **out,+ size_t *out_len, size_t max);int bpm_pkg_read_member(const char *archive, const char *member,__u8 **out, size_t *out_len, size_t max);/*diff --git a/util/crypto.h b/util/crypto.hindex 4c6e6df8..f6655787 100644--- a/util/crypto.h+++ b/util/crypto.h@@ -123,6 +123,9 @@ int base64_decode(const char *in, size_t in_len, __u8 *out,int cert_read_der(const __u8 *der, size_t len,struct cert *cert) __must_check;+/* A DER or a PEM certificate, as cert_read_file() takes from a file. */+int cert_read_memory(const __u8 *buf, size_t len,+ struct cert *cert) __must_check;struct cert_pubkey {bool rsa;diff --git a/util/crypto_openssl.c b/util/crypto_openssl.cindex a60e50c9..3524712f 100644--- a/util/crypto_openssl.c+++ b/util/crypto_openssl.c@@ -611,6 +611,27 @@ int cert_read_der(const __u8 *der, size_t len,return cert->impl ? 0 : -EINVAL;}+int cert_read_memory(const __u8 *buf, size_t len, struct cert *cert)+{+ BIO *bio;++ if (!buf || !cert || len > INT_MAX)+ return -EINVAL;+ if (!cert_read_der(buf, len, cert))+ return 0;+ ERR_clear_error();+ bio = BIO_new_mem_buf(buf, (int)len);+ if (!bio)+ return -ENOMEM;+ cert->impl = PEM_read_bio_X509(bio, NULL, NULL, NULL);+ BIO_free(bio);+ if (!cert->impl) {+ ERR_clear_error();+ return -EINVAL;+ }+ return 0;+}+int cert_pubkey(const struct cert *cert,struct cert_pubkey *out){diff --git a/util/upatch_maps_otel.c b/util/upatch_maps_otel.cindex 59799df1..fceefdb6 100644--- a/util/upatch_maps_otel.c+++ b/util/upatch_maps_otel.c@@ -16,6 +16,7 @@#include <stdio.h>#include <stdlib.h>#include <string.h>+#include <sys/mman.h>#include <sys/random.h>#include <sys/stat.h>#include <time.h>@@ -1446,34 +1447,18 @@ struct snapshot_writer {bool deflate_ready;};+/*+ * In memory: a file under TMPDIR, which root sets, could be created in a+ * sealed directory, labeled.+ */static int snapshot_temp_file(FILE **out){- const char *tmpdir = getenv("TMPDIR");- char path[PATH_MAX];FILE *file;int fd;- if (!tmpdir || !tmpdir[0])- tmpdir = "/tmp";- if (strsprintf(path, sizeof(path), "%s/%s", tmpdir,- "shirudo-map-snapshot.XXXXXX") < 0)- return -ENAMETOOLONG;- fd = mkstemp(path);+ fd = memfd_create("shirudo-map-snapshot", MFD_CLOEXEC);if (fd < 0)return -errno;- if (fchmod(fd, 0600) != 0) {- int ret = -errno;-- unlink(path);- close(fd);- return ret;- }- if (unlink(path) != 0) {- int ret = -errno;-- close(fd);- return ret;- }file = fdopen(fd, "w+b");if (!file) {int ret = -errno;