eBPF-based security platform
overflow: check size arithmetic with the kernel's helpers
Daniel Borkmann60a590051e8b
diff --git a/AGENTS.md b/AGENTS.mdindex 03a4c431..b76df4cf 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -108,6 +108,13 @@ package for `bpm info`.they take a length, read nothing past it and refuse a sign, blank orbase prefix. `<shirudo/string.h>` poisons `strtoul()` and its kin and`atoi()`, and `check-style.sh` rejects them outside `testing/`.+- **Check size and length arithmetic with the helpers of+ `<shirudo/overflow.h>`**: `check_add_overflow()`,+ `check_sub_overflow()` and `check_mul_overflow()` say whether the+ result fits the destination, and `size_add()`, `size_sub()`,+ `size_mul()` and `struct_size()` stick at `SIZE_MAX`, so the+ allocation they size fails. Not `a > SIZE_MAX - b` or+ `n > SIZE_MAX / size` by hand.- **Copy strings with `strscpy()` and format into a fixed buffer with`strsprintf()`**, or `vstrsprintf()` from a `va_list`, all from`<shirudo/string.h>`: `strscpy()` always terminates and returnsdiff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 2675dc83..be3089b2 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -434,9 +434,10 @@ Unit suites and fuzz targetsThe unit suites in :src:`testing/unit/` cover seven of the modules in:src:`util/`: ``chain``, ``hex``, ``json``, ``kernel_abi``,-``kernel_build_id``, ``kernel_release`` and ``string``. The other-modules are reached through the test helpers, the fuzz targets and the-binaries the functional tests run.+``kernel_build_id``, ``kernel_release`` and ``string``, and ``overflow``+the arithmetic of :src:`include/shirudo/overflow.h`. The other modules+are reached through the test helpers, the fuzz targets and the binaries+the functional tests run... list-table:::header-rows: 1diff --git a/builtin-bpm.c b/builtin-bpm.cindex 5f0b05d1..4deb92da 100644--- a/builtin-bpm.c+++ b/builtin-bpm.c@@ -29,6 +29,7 @@#include <openssl/x509.h>#include <shirudo/misc.h>+#include <shirudo/overflow.h>#include <shirudo/string.h>#include "builtin.h"@@ -545,9 +546,9 @@ static int print_upatch_member(void *ctx, const char *member, char type)return 0;if (len <= sizeof(prefix) - 1 || strchr(member + sizeof(prefix) - 1, '/'))return 0;- if (len > SIZE_MAX - opts->len - 1)+ if (check_add_overflow(opts->len, len, &need) ||+ check_add_overflow(need, 1, &need))return -EOVERFLOW;- need = opts->len + len + 1;if (need > opts->cap) {cap = opts->cap ? opts->cap : 4096;while (cap < need) {diff --git a/include/shirudo/overflow.h b/include/shirudo/overflow.hnew file mode 100644index 00000000..252fa6d9--- /dev/null+++ b/include/shirudo/overflow.h@@ -0,0 +1,80 @@+/* SPDX-License-Identifier: BSD-2-Clause */+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * Integer arithmetic that reports or saturates instead of wrapping.+ */++#ifndef SHIRUDO_OVERFLOW_H+#define SHIRUDO_OVERFLOW_H++#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>++#include <shirudo/compiler.h>+#include <shirudo/misc.h>++static inline bool __must_check __must_check_overflow(bool overflow)+{+ return overflow;+}++/*+ * true when a + b, a - b or a * b, taken over the mathematical integers,+ * does not fit the type d points to. *d holds the result wrapped to that+ * type either way. a and b may be of any integer type and need not match+ * each other or *d.+ */+#define check_add_overflow(a, b, d) \+ __must_check_overflow(__builtin_add_overflow(a, b, d))+#define check_sub_overflow(a, b, d) \+ __must_check_overflow(__builtin_sub_overflow(a, b, d))+#define check_mul_overflow(a, b, d) \+ __must_check_overflow(__builtin_mul_overflow(a, b, d))++/*+ * Sizes that stick at SIZE_MAX once a step does not fit, and stay there+ * through the steps after it, so that the allocation or bound they reach+ * fails rather than come out short.+ */+static inline size_t __must_check size_add(size_t a, size_t b)+{+ size_t bytes;++ if (check_add_overflow(a, b, &bytes))+ return SIZE_MAX;+ return bytes;+}++static inline size_t __must_check size_mul(size_t a, size_t b)+{+ size_t bytes;++ if (check_mul_overflow(a, b, &bytes))+ return SIZE_MAX;+ return bytes;+}++static inline size_t __must_check size_sub(size_t a, size_t b)+{+ size_t bytes;++ if (a == SIZE_MAX || b == SIZE_MAX || check_sub_overflow(a, b, &bytes))+ return SIZE_MAX;+ return bytes;+}++/*+ * The size of *p with count elements in its flexible array member, which+ * has to be an array and not a pointer.+ */+#define __flex_array_size(a, count) \+ size_mul(sizeof(typeof((a)[0])) + \+ BUILD_BUG_ON_ZERO(__builtin_types_compatible_p(typeof(a), \+ typeof((a)[0]) *)), count)+#define struct_size(p, member, count) \+ size_add(sizeof(typeof((p)[0])), \+ __flex_array_size((p)[0].member, count))++#endif /* SHIRUDO_OVERFLOW_H */diff --git a/testing/helper/test-exec-churn.c b/testing/helper/test-exec-churn.cindex be18961a..89ce1723 100644--- a/testing/helper/test-exec-churn.c+++ b/testing/helper/test-exec-churn.c@@ -12,6 +12,7 @@#include <unistd.h>#include <shirudo/misc.h>+#include <shirudo/overflow.h>#include "io.h"@@ -98,10 +99,10 @@ int main(int argc, char **argv)if (!duration_sec || !workers || workers > 1024)return 2;start = monotonic_ns();- if (!start || duration_sec > UINT64_MAX / 1000000000ULL ||- start > UINT64_MAX - duration_sec * 1000000000ULL)+ if (!start ||+ check_mul_overflow(duration_sec, 1000000000ULL, &deadline) ||+ check_add_overflow(deadline, start, &deadline))return 1;- deadline = start + duration_sec * 1000000000ULL;if (pipe(result_fd) != 0)return 1;children = calloc(workers, sizeof(*children));diff --git a/testing/unit/overflow.c b/testing/unit/overflow.cnew file mode 100644index 00000000..5bbf0d29--- /dev/null+++ b/testing/unit/overflow.c@@ -0,0 +1,69 @@+// SPDX-License-Identifier: BSD-2-Clause+/* Copyright (c) 2026 Authors of shirudo */++#include <stdint.h>++#include <shirudo/overflow.h>++#include "unit.h"++struct flex {+ __u64 head;+ __u32 tail[];+};++static void check_overflow_judges_by_the_destination(void)+{+ __u64 u64;+ size_t sz;+ __u32 u32;+ __u8 u8;+ __s8 s8;++ EXPECT_FALSE(check_add_overflow(200, 55, &u8));+ EXPECT_EQ(u8, 255);+ EXPECT_TRUE(check_add_overflow(200, 56, &u8));+ EXPECT_EQ(u8, 0);+ EXPECT_FALSE(check_add_overflow((__u32)UINT32_MAX, 1, &u64));+ EXPECT_UEQ(u64, 1ULL << 32);+ EXPECT_TRUE(check_add_overflow((size_t)SIZE_MAX, 1, &sz));+ EXPECT_TRUE(check_sub_overflow(0u, 1u, &u32));+ EXPECT_FALSE(check_sub_overflow(0, 1, &s8));+ EXPECT_EQ(s8, -1);+ EXPECT_TRUE(check_sub_overflow(-100, 100, &s8));+ EXPECT_FALSE(check_mul_overflow(SIZE_MAX / 2, 2, &sz));+ EXPECT_UEQ(sz, SIZE_MAX - 1);+ EXPECT_TRUE(check_mul_overflow(SIZE_MAX / 2 + 1, 2, &sz));+ EXPECT_TRUE(check_mul_overflow(0x10000u, 0x10000u, &u32));+}++static void sizes_stick_at_size_max(void)+{+ EXPECT_UEQ(size_add(2, 3), 5);+ EXPECT_UEQ(size_add(SIZE_MAX, 1), SIZE_MAX);+ EXPECT_UEQ(size_mul(4, 5), 20);+ EXPECT_UEQ(size_mul(SIZE_MAX / 2 + 1, 2), SIZE_MAX);+ EXPECT_UEQ(size_sub(5, 3), 2);+ EXPECT_UEQ(size_sub(3, 5), SIZE_MAX);+ EXPECT_UEQ(size_sub(SIZE_MAX, 1), SIZE_MAX);+ EXPECT_UEQ(size_sub(10, SIZE_MAX), SIZE_MAX);+ EXPECT_UEQ(size_add(size_mul(SIZE_MAX, 2), 1), SIZE_MAX);+}++static void struct_size_counts_the_flexible_array(void)+{+ struct flex *p = NULL;++ EXPECT_UEQ(struct_size(p, tail, 0), sizeof(*p));+ EXPECT_UEQ(struct_size(p, tail, 3), sizeof(*p) + 3 * sizeof(__u32));+ EXPECT_UEQ(struct_size(p, tail, SIZE_MAX / 4), SIZE_MAX);+}++static const struct unit_case cases[] = {+ UNIT_CASE(check_overflow_judges_by_the_destination),+ UNIT_CASE(sizes_stick_at_size_max),+ UNIT_CASE(struct_size_counts_the_flexible_array),+ {}+};++UNIT_SUITE(overflow, cases);diff --git a/tools/shirudo-build/package.c b/tools/shirudo-build/package.cindex e02f1784..191ef77a 100644--- a/tools/shirudo-build/package.c+++ b/tools/shirudo-build/package.c@@ -22,6 +22,7 @@#include <bpf/libbpf.h>#include <shirudo/misc.h>+#include <shirudo/overflow.h>#include <shirudo/string.h>#include <shirudo/upatch.h>@@ -818,10 +819,9 @@ static int make_decoder_path(const char *src_path, const char *rel,if (slash)dir_len = (size_t)(slash - src_path) + 1;}- if (dir_len > UINT32_MAX || rel_len > UINT32_MAX - 1 ||- dir_len > UINT32_MAX - rel_len - 1)+ if (check_add_overflow(dir_len, rel_len, &len) ||+ check_add_overflow(len, 1, &len) || len > UINT32_MAX)return -EOVERFLOW;- len = dir_len + rel_len + 1;path = xmalloc(len);if (!path)return -ENOMEM;@@ -1181,10 +1181,9 @@ static int build_prog_metadata(struct bpf_object *obj, __u32 nr_progs,if (err)return err;}- if (nr_progs >- (UINT32_MAX - sizeof(*md)) / sizeof(md->progs[0]))+ base_len = struct_size(md, progs, nr_progs);+ if (base_len > UINT32_MAX)return -EOVERFLOW;- base_len = sizeof(*md) + (size_t)nr_progs * sizeof(md->progs[0]);len = base_len;md_alloc_len = base_len;md = xmalloc(len);@@ -1383,22 +1382,26 @@ static int build_prog_metadata(struct bpf_object *obj, __u32 nr_progs,__u8 *cursor;__u32 j;- if (len > UINT32_MAX - sizeof(targets)) {+ if (check_add_overflow(len, sizeof(targets), &len) ||+ len > UINT32_MAX) {err = -EOVERFLOW;goto err_free;}- len += sizeof(targets);for (j = 0; j < nr_uprobe_targets; j++) {const struct build_uprobe_target *ut = &uprobe_targets[j];- size_t record_len = sizeof(struct upatch_uprobe_target) +- ut->path_len + ut->elf.build_id_len +- (size_t)ut->elf.nr_offsets * sizeof(__u64);-- if (record_len > UINT32_MAX || len > UINT32_MAX - record_len) {+ size_t record_len;++ record_len = size_add(sizeof(struct upatch_uprobe_target),+ size_add(ut->path_len,+ ut->elf.build_id_len));+ record_len = size_add(record_len,+ size_mul(ut->elf.nr_offsets,+ sizeof(__u64)));+ if (check_add_overflow(len, record_len, &len) ||+ len > UINT32_MAX) {err = -EOVERFLOW;goto err_free;}- len += record_len;}{void *grown = xreallocarray(md, base_len, len, 1);diff --git a/util/image_cache.c b/util/image_cache.cindex 044d2065..c7c66da6 100644--- a/util/image_cache.c+++ b/util/image_cache.c@@ -2,6 +2,7 @@/* Copyright (c) 2026 Authors of shirudo */#include <shirudo/misc.h>+#include <shirudo/overflow.h>#include <shirudo/string.h>#include <errno.h>@@ -38,11 +39,10 @@ static size_t download_write(char *data, size_t size, size_t count, void *ctx)size_t bytes;int ret;- if (size && count > SIZE_MAX / size) {+ if (check_mul_overflow(size, count, &bytes)) {download->err = -EFBIG;return 0;}- bytes = size * count;if (bytes > download->limit - download->written) {download->err = -EFBIG;return 0;diff --git a/util/malloc.c b/util/malloc.cindex bcf65deb..e3cee01b 100644--- a/util/malloc.c+++ b/util/malloc.c@@ -12,6 +12,7 @@#include <string.h>#include <shirudo/misc.h>+#include <shirudo/overflow.h>/* xasprintf() formats with vsnprintf(), which <shirudo/string.h> poisons. */#define STRING_INTERNAL@@ -32,14 +33,16 @@ void *xmalloc(size_t size)void *xcalloc(size_t nmemb, size_t size){+ size_t bytes;+/** Reject a multiply that would wrap before it reaches the* allocator -- a caller computing nmemb * size itself would miss* it. xmalloc() zero-initialises and handles the zero case.*/- if (nmemb && size && nmemb > SIZE_MAX / size)+ if (check_mul_overflow(nmemb, size, &bytes))return NULL;- return xmalloc(nmemb * size);+ return xmalloc(bytes);}void *xreallocarray(void *ptr, size_t old_nmemb, size_t new_nmemb,@@ -48,11 +51,9 @@ void *xreallocarray(void *ptr, size_t old_nmemb, size_t new_nmemb,size_t old_size, new_size, copy;void *out;- if (size && (new_nmemb > SIZE_MAX / size ||- old_nmemb > SIZE_MAX / size))+ if (check_mul_overflow(old_nmemb, size, &old_size) ||+ check_mul_overflow(new_nmemb, size, &new_size))return NULL; /* overflow -- leave ptr untouched */- old_size = old_nmemb * size;- new_size = new_nmemb * size;out = xmalloc(new_size); /* zeroed; the grown tail starts at 0 */if (!out)diff --git a/util/sign.c b/util/sign.cindex 6e8dbcc9..ce836a66 100644--- a/util/sign.c+++ b/util/sign.c@@ -32,6 +32,8 @@#include <openssl/pem.h>#include <openssl/x509.h>+#include <shirudo/overflow.h>+#include "log.h"#include "malloc.h"#include "sign.h"@@ -185,11 +187,11 @@ int cms_sign(struct sign_io *io,* the concatenation the kernel folds and verifies at load. Build* that once and feed it to both CMS_final and the digest.*/- if (io->insns_sz > INT_MAX || io->data_sz > INT_MAX - io->insns_sz) {+ if (check_add_overflow(io->insns_sz, io->data_sz, &content_sz) ||+ content_sz > INT_MAX) {err = -E2BIG;goto cleanup;}- content_sz = io->insns_sz + io->data_sz;content = xmalloc(content_sz);if (!content) {err = -ENOMEM;diff --git a/util/upatch.c b/util/upatch.cindex 52526ba8..8b7e417e 100644--- a/util/upatch.c+++ b/util/upatch.c@@ -15,6 +15,7 @@#include <unistd.h>#include <shirudo/misc.h>+#include <shirudo/overflow.h>#include "malloc.h"#include "upatch.h"@@ -499,11 +500,9 @@ int prog_specs_parse(const void *metadata, __u32 metadata_len,return -EOPNOTSUPP;if (count != nr_progs || le32_to_cpu(md.reserved) != 0)return -EINVAL;- if (count > (UINT32_MAX - sizeof(md)) /- sizeof(struct upatch_prog_entry))+ base_len = struct_size(&md, progs, count);+ if (base_len > UINT32_MAX)return -EOVERFLOW;- base_len = sizeof(md) + (size_t)count *- sizeof(struct upatch_prog_entry);if (metadata_len < base_len)return -EINVAL;specs = xcalloc(nr_progs, sizeof(*specs));diff --git a/util/upatch_decode.c b/util/upatch_decode.cindex db8a522f..656624d6 100644--- a/util/upatch_decode.c+++ b/util/upatch_decode.c@@ -81,6 +81,7 @@ int upatch_decode_map_file_otel(const char *path,#include <luajit.h>#include <shirudo/misc.h>+#include <shirudo/overflow.h>#include <shirudo/string.h>#include "json.h"@@ -872,11 +873,12 @@ static int lua_check_u64_string(lua_State *L, int arg, __u64 *out)/* Exact 64-bit arithmetic on decimal strings; Lua numbers lose nanoseconds. */static int lua_shirudo_u64_add(lua_State *L){- __u64 a, b;+ __u64 a, b, sum;lua_check_u64_string(L, 1, &a);lua_check_u64_string(L, 2, &b);- lua_push_u64_string(L, a > UINT64_MAX - b ? UINT64_MAX : a + b);+ lua_push_u64_string(L, check_add_overflow(a, b, &sum) ?+ UINT64_MAX : sum);return 1;}diff --git a/util/upatch_maps.c b/util/upatch_maps.cindex 76a7521a..538f0b00 100644--- a/util/upatch_maps.c+++ b/util/upatch_maps.c@@ -23,6 +23,7 @@#include <bpf/libbpf.h>#include <shirudo/misc.h>+#include <shirudo/overflow.h>#include <shirudo/string.h>#include <shirudo/upatch.h>@@ -1083,10 +1084,9 @@ static int read_entries(int fd, struct map_view *v,__u32 i;int err;- if (upatch_map_value_stride(v) != 0 &&- value_count > SIZE_MAX / upatch_map_value_stride(v))+ if (check_mul_overflow(upatch_map_value_stride(v), value_count,+ &value_alloc))return -EOVERFLOW;- value_alloc = (size_t)upatch_map_value_stride(v) * value_count;v->entries = NULL;v->n_entries = 0;diff --git a/util/upatch_maps_otel.c b/util/upatch_maps_otel.cindex 2a6786b1..53b4255f 100644--- a/util/upatch_maps_otel.c+++ b/util/upatch_maps_otel.c@@ -29,6 +29,7 @@#include <zlib.h>#include <shirudo/misc.h>+#include <shirudo/overflow.h>#include <shirudo/string.h>#include <shirudo/upatch.h>@@ -1823,13 +1824,15 @@ static int snapshot_temp_file(FILE **out)static int snapshot_write_compressed(struct snapshot_writer *w,const __u8 *data, size_t len){- if (UINT64_MAX - w->object_bytes < len)+ __u64 total;++ if (check_add_overflow(w->object_bytes, len, &total))return -EOVERFLOW;if (len && fwrite(data, 1, len, w->file) != len)return -EIO;if (len && sha256_update(&w->md, data, len) != 0)return -EIO;- w->object_bytes += len;+ w->object_bytes = total;return 0;}@@ -1867,9 +1870,8 @@ static int snapshot_json_sink(void *ctx, const char *data, size_t len)struct snapshot_writer *w = ctx;__u8 out[S3_GZIP_BUFFER_SIZE];- if (UINT64_MAX - w->json_bytes < len)+ if (check_add_overflow(w->json_bytes, len, &w->json_bytes))return -EOVERFLOW;- w->json_bytes += len;while (len) {uInt chunk = len > UINT_MAX ? UINT_MAX : (uInt)len;@@ -2074,9 +2076,10 @@ static int parse_s3_spec(struct otel_s3_state *st, const char *spec)if (!access || !access[0] || !secret || !secret[0] ||strpbrk(access, "\r\n:") || strpbrk(secret, "\r\n"))return -EACCES;- if (strlen(access) > SIZE_MAX - strlen(secret) - 2)+ if (check_add_overflow(strlen(access), strlen(secret),+ &credentials_len) ||+ check_add_overflow(credentials_len, 2, &credentials_len))return -EOVERFLOW;- credentials_len = strlen(access) + strlen(secret) + 2;st->credentials = xmalloc(credentials_len);if (!st->credentials)return -ENOMEM;