eBPF-based security platform
string: compare with a literal without counting its length by hand
Daniel Borkmann6b4cfcb97d2c
diff --git a/.agents/skills/coding/SKILL.md b/.agents/skills/coding/SKILL.mdindex 1c006416..442df0ba 100644--- a/.agents/skills/coding/SKILL.md+++ b/.agents/skills/coding/SKILL.md@@ -269,6 +269,7 @@ already, or should. The basics:| Parse a number | `parse_u64()`, `parse_s64()`, `parse_x64()`, `digits()` (`<shirudo/string.h>`) || Copy or format a string | `strscpy()`, `strsprintf()`, `vstrsprintf()`, and check `-E2BIG` || An upatch's pin directory or a pin in it | `upatch_pin_path()` (`util/paths.h`) |+| A string's prefix, or a span that must be one literal | `str_has_prefix()` to test a prefix, `str_skip_prefix()` to step past it, `span_equals()` for a span of known length (`<shirudo/string.h>`); never `strncmp()` with a length counted by hand || A file name's extension | `name_has_suffix()` (`<shirudo/string.h>`), `upatch_select()` for a scandir of upatches || Text from outside on a terminal | `text_sanitize()`; UTF-8 with `utf8_width()` || Sizes and lengths | `check_add_overflow()` and kin, `size_add()`, `size_mul()`, `struct_size()` (`<shirudo/overflow.h>`) |diff --git a/builtin-attest.c b/builtin-attest.cindex 204e0c9d..b81ac1c1 100644--- a/builtin-attest.c+++ b/builtin-attest.c@@ -211,20 +211,20 @@ static int apply_event(const char *spec, __u8 chain[32])if (!colon || attest_parse_name_digest(colon + 1, name, digest))return -EINVAL;kind_len = (size_t)(colon - spec);- if (kind_len == 4 && !strncmp(spec, "load", 4)) {+ if (span_equals(spec, kind_len, "load")) {if (chain_upatch_event("shirudo-upatch", name, digest, event))return -EIO;- } else if (kind_len == 6 && !strncmp(spec, "unload", 6)) {+ } else if (span_equals(spec, kind_len, "unload")) {if (chain_upatch_event("shirudo-unload", name, digest, event))return -EIO;- } else if (kind_len == 4 && !strncmp(spec, "tree", 4)) {+ } else if (span_equals(spec, kind_len, "tree")) {__s64 seq;if (parse_s64(name, strlen(name), 1, INT64_MAX, &seq))return -EINVAL;if (chain_tree_event(seq, digest, event))return -EIO;- } else if (kind_len == 6 && !strncmp(spec, "revoke", 6)) {+ } else if (span_equals(spec, kind_len, "revoke")) {if (chain_key_event("shirudo-key-revoke", digest, event))return -EIO;} else {@@ -477,18 +477,20 @@ static int report_emit_json(const char *report, const char *verdict)const char *nl = strchr(line, '\n');size_t len = nl ? (size_t)(nl - line) : strlen(line);char text[ATTEST_REPORT_MAX];- const char *kind = NULL;+ const char *kind = NULL, *rest = line;+ size_t mark;- if (len > 8 && !strncmp(line, " OK ", 8))+ if (str_skip_prefix(&rest, " OK "))kind = "ok";- else if (len > 8 && !strncmp(line, " FAIL ", 8))+ else if (str_skip_prefix(&rest, " FAIL "))kind = "fail";- else if (len > 8 && !strncmp(line, " NOTE ", 8))+ else if (str_skip_prefix(&rest, " NOTE "))kind = "note";- if (kind) {- size_t n = min(len - 8, sizeof(text) - 1);+ mark = (size_t)(rest - line);+ if (kind && len > mark) {+ size_t n = min(len - mark, sizeof(text) - 1);- memcpy(text, line + 8, n);+ memcpy(text, rest, n);text[n] = '\0';json_obj_open(&e);json_kv_string(&e, "result", kind);diff --git a/builtin-bpm.c b/builtin-bpm.cindex 0eef6654..c49bf851 100644--- a/builtin-bpm.c+++ b/builtin-bpm.c@@ -425,7 +425,7 @@ static int load_source(const char *name, struct bpm_source *s)return ret;/* With a config image the key file is the image's, named from its root. */if (image_config_active()) {- if (!strncmp(s->key_file, "/etc/shirudo/bpm/keys/", 22))+ if (str_has_prefix(s->key_file, "/etc/shirudo/bpm/keys/"))memmove(s->key_file, s->key_file + 1,strlen(s->key_file));if (s->key_file[0] == '/' || strstr(s->key_file, ".."))@@ -537,7 +537,7 @@ static int package_source_open(const char *source){int fd, ret;- if (strncmp(source, "oci://", 6)) {+ if (!str_has_prefix(source, "oci://")) {fd = open(source, O_RDONLY | O_CLOEXEC);return fd < 0 ? -errno : fd;}@@ -596,15 +596,13 @@ struct bpm_upatches_ctx {static int print_upatch_member(void *ctx, const char *member, char type){struct bpm_upatches_ctx *opts = ctx;- static const char prefix[] = "upatches/";size_t len = strlen(member), need, cap;enum bpm_upatch_member kind;- const char *base;+ const char *base = member;char *next;- if (type != '0' || strncmp(member, prefix, sizeof(prefix) - 1))+ if (type != '0' || !str_skip_prefix(&base, "upatches/"))return 0;- base = member + sizeof(prefix) - 1;if (strchr(base, '/'))return 0;kind = bpm_upatch_member(base, strlen(base));@@ -671,14 +669,14 @@ static int print_package_upatch_data(const char *source, const char *member,{size_t beefile_len = 0, upatch_len = 0;__u8 *beefile = NULL, *bytes = NULL;+ const char *base = member;char package_dir[101];struct upatch u = {};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)+ if (!bpm_archive_rel_ok(member) ||+ !str_skip_prefix(&base, "upatches/") || strchr(base, '/') ||+ bpm_upatch_member(base, strlen(base)) == BPM_UPATCH_OTHER)return -EINVAL;fd = package_source_open(source);if (fd < 0)@@ -868,7 +866,7 @@ static int key_source_read(const char *source, __u8 **der, size_t *len,size_t n = strlen(source);int fd, ret;- if (strncmp(source, "oci://", 6) &&+ if (!str_has_prefix(source, "oci://") &&!name_has_suffix(source, n, ".bee")) {ret = keys_read_der(source, der, len);*cap = *len;@@ -1186,7 +1184,7 @@ static int package_install(const struct bpm_source *s, const struct bpm_index_en* Repository indexes carry a sha256 manifest digest; direct OCI* references carry the tag in this field and cannot be digest-checked.*/- if (!strncmp(entry->manifest_digest, "sha256:", 7)) {+ if (str_has_prefix(entry->manifest_digest, "sha256:")) {char manifest_hex[65];if (bpm_sha256_hex(manifest.data, manifest.len, manifest_hex,@@ -2889,7 +2887,7 @@ static int bpm_install(const char *ref, struct bpm_tables *t)char source[BPM_MAX_NAME], name[BPM_MAX_NAME], version[BPM_MAX_NAME];struct bpm_index_entry *entries = t->entries;struct bpm_state_entry *state = t->state;- bool direct = !strncmp(ref, "oci://", 6);+ bool direct = str_has_prefix(ref, "oci://");struct bpm_index_entry selected;struct bpm_source source_cfg;int n_entries, n_state, lock, ret, i;diff --git a/builtin-upatch.c b/builtin-upatch.cindex 8fc9fa61..081173b1 100644--- a/builtin-upatch.c+++ b/builtin-upatch.c@@ -1756,7 +1756,7 @@ static int pin_upatch_maps(const struct loader_ctx *cx,if (strchr(info.name, '.'))continue;/* upatch-private maps are intentionally not operator-visible. */- if (strncmp(info.name, "obs_i_", 6) == 0)+ if (str_has_prefix(info.name, "obs_i_"))continue;if (strsprintf(pin, sizeof(pin), "%s/%s", maps_dir,info.name) < 0)diff --git a/include/shirudo/string.h b/include/shirudo/string.hindex b0cb4c06..0bb7926f 100644--- a/include/shirudo/string.h+++ b/include/shirudo/string.h@@ -4,7 +4,8 @@** Bounded number parsing, string copies and formatting, file name* suffixes, DNS names, UTF-8 characters and text for a terminal, from- * util/string.c, and the scrub and compare for secrets.+ * util/string.c, compares with a string literal, and the scrub and compare+ * for secrets.*/#ifndef SHIRUDO_STRING_H@@ -59,6 +60,34 @@ int vstrsprintf(char *buf, size_t size, const char *fmt, va_list ap)*/bool name_has_suffix(const char *name, size_t len, const char *suffix);+/*+ * The length of prefix where s starts with it, else 0. prefix is a string+ * literal, whose length the compiler takes from its size: anything else+ * fails the build, so that the size of a pointer never stands in for it.+ */+#define str_has_prefix(s, prefix) \+ (strncmp(s, "" prefix, sizeof(prefix) - 1) ? 0 : sizeof(prefix) - 1)++/*+ * Whether *sp starts with the string literal prefix; where it does, *sp+ * moves past it. Where a test after it fails, *sp has still moved, so a+ * chain that tests the rest of the string takes str_has_prefix().+ */+#define str_skip_prefix(sp, prefix) ({ \+ __auto_type __sp = (sp); \+ size_t __n = str_has_prefix(*__sp, prefix); \+ \+ *__sp += __n; \+ __n != 0; \+})++/*+ * Whether the len bytes at s are the string literal lit, no more and no+ * fewer, its length again taken from its size.+ */+#define span_equals(s, len, lit) \+ ((len) == sizeof(lit) - 1 && !strncmp(s, "" lit, sizeof(lit) - 1))+/** A DNS host name: labels of letters, digits and inner hyphens, 1 to 63* bytes each and 253 in all. A name whose labels are all decimal or 0xdiff --git a/testing/unit/string.c b/testing/unit/string.cindex 72bdac31..171ff90b 100644--- a/testing/unit/string.c+++ b/testing/unit/string.c@@ -489,6 +489,44 @@ static void name_has_suffix_wants_a_stem(void)EXPECT_TRUE(name_has_suffix("a", 1, ""));}+#define TEST_DIR "/run"++static void str_has_prefix_gives_its_length(void)+{+ EXPECT_UEQ(str_has_prefix("oci://registry", "oci://"), 6);+ EXPECT_UEQ(str_has_prefix("oci://", "oci://"), 6);+ EXPECT_UEQ(str_has_prefix("oci:/", "oci://"), 0);+ EXPECT_UEQ(str_has_prefix("OCI://registry", "oci://"), 0);+ EXPECT_UEQ(str_has_prefix("", "oci://"), 0);+ EXPECT_UEQ(str_has_prefix("/run/x", TEST_DIR "/"), 5);+}++static void str_skip_prefix_moves_only_on_a_match(void)+{+ const char *p = "realm=\"x\"";+ char buf[] = "s3://bucket";+ char *q = buf;++ EXPECT_FALSE(str_skip_prefix(&p, "scope=\""));+ EXPECT_STREQ(p, "realm=\"x\"");+ EXPECT_TRUE(str_skip_prefix(&p, "realm=\""));+ EXPECT_STREQ(p, "x\"");+ EXPECT_TRUE(str_skip_prefix(&q, "s3://"));+ EXPECT_TRUE(q == buf + 5);+}++static void span_equals_wants_the_whole_literal(void)+{+ const char *path = "a/../b";++ EXPECT_TRUE(span_equals(path + 2, 2, ".."));+ EXPECT_FALSE(span_equals(path + 2, 3, ".."));+ EXPECT_FALSE(span_equals(path + 2, 1, ".."));+ EXPECT_TRUE(span_equals(path + 2, 1, "."));+ EXPECT_FALSE(span_equals(path, 1, "."));+ EXPECT_TRUE(span_equals(path, 0, ""));+}+static const struct unit_case cases[] = {UNIT_CASE(digits_counts_leading_digits),UNIT_CASE(decimal_fills_its_span),@@ -512,6 +550,9 @@ static const struct unit_case cases[] = {UNIT_CASE(memzero_explicit_clears_its_span_only),UNIT_CASE(memneq_explicit_tells_every_bit_apart),UNIT_CASE(name_has_suffix_wants_a_stem),+ UNIT_CASE(str_has_prefix_gives_its_length),+ UNIT_CASE(str_skip_prefix_moves_only_on_a_match),+ UNIT_CASE(span_equals_wants_the_whole_literal),{}};diff --git a/tools/shirudo-build/bpm-build.c b/tools/shirudo-build/bpm-build.cindex a4e618b8..9aea7da6 100644--- a/tools/shirudo-build/bpm-build.c+++ b/tools/shirudo-build/bpm-build.c@@ -524,8 +524,7 @@ static int build_parse_spec(struct bpm_build_spec *spec, char *body)return -ENOMEM;}sel = tree_owner->tree.selector;- } else if (!strncmp(section, "upatches.tree",- strlen("upatches.tree"))) {+ } else if (str_has_prefix(section, "upatches.tree")) {/** A selector the builder cannot read would* widen the rollout.@@ -1027,8 +1026,8 @@ static int build_target_ok(const char *target)const char *q = strchr(p, '/');size_t n = q ? (size_t)(q - p) : strlen(p);- if (!n || (n == 1 && *p == '.') ||- (n == 2 && !strncmp(p, "..", 2)) || (q && !q[1]))+ if (!n || span_equals(p, n, ".") || span_equals(p, n, "..") ||+ (q && !q[1]))return -EINVAL;p = q ? q + 1 : p + n;}@@ -2055,7 +2054,7 @@ static int __build_bpm_config_update(int argc, char **argv,struct bpm_build_input_override *overrides){const char *file_arg = NULL, *base_arg = NULL, *base_digest = NULL;- const char *version = NULL, *keys_arg = NULL;+ const char *version = NULL, *keys_arg = NULL, *base_hex;size_t n_overrides = 0;char build_file[PATH_MAX], resolved_file[PATH_MAX], source_dir[PATH_MAX];char base_package[PATH_MAX], base_package_tmp[] =@@ -2127,13 +2126,13 @@ static int __build_bpm_config_update(int argc, char **argv,version);return -EINVAL;}- if (!strncmp(base_arg, "oci://", 6) != !!base_digest) {+ if (!!str_has_prefix(base_arg, "oci://") != !!base_digest) {pr_err("bpm config update: --base-digest names the manifest of an oci:// base package, and one needs it");return -EINVAL;}- if (base_digest && (strncmp(base_digest, "sha256:", 7) ||- strlen(base_digest + 7) != 64 ||- !hex_is_lower(base_digest + 7, 64))) {+ base_hex = base_digest;+ if (base_hex && (!str_skip_prefix(&base_hex, "sha256:") ||+ strlen(base_hex) != 64 || !hex_is_lower(base_hex, 64))) {pr_err("bpm config update: --base-digest %s is not sha256:<64 lowercase hex>",base_digest);return -EINVAL;diff --git a/tools/shirudo-build/package.c b/tools/shirudo-build/package.cindex d6faf3bc..16c46802 100644--- a/tools/shirudo-build/package.c+++ b/tools/shirudo-build/package.c@@ -536,8 +536,8 @@ static bool unsupported_kprobe_section(const char *sec)strcmp(sec, "kretprobe") == 0 ||strcmp(sec, "kprobe/") == 0 ||strcmp(sec, "kretprobe/") == 0 ||- strncmp(sec, "kprobe.multi", 12) == 0 ||- strncmp(sec, "kretprobe.multi", 15) == 0);+ str_has_prefix(sec, "kprobe.multi") ||+ str_has_prefix(sec, "kretprobe.multi"));}/*@@ -582,11 +582,11 @@ static bool unsupported_uprobe_section(const char *sec)if (uprobe_section_target(sec, &kind))return false;return strcmp(sec, "uprobe") == 0 ||- strncmp(sec, "uprobe/", 7) == 0 ||- strncmp(sec, "uprobe.", 7) == 0 ||+ str_has_prefix(sec, "uprobe/") ||+ str_has_prefix(sec, "uprobe.") ||strcmp(sec, "uretprobe") == 0 ||- strncmp(sec, "uretprobe/", 10) == 0 ||- strncmp(sec, "uretprobe.", 10) == 0;+ str_has_prefix(sec, "uretprobe/") ||+ str_has_prefix(sec, "uretprobe.");}static bool unsupported_sk_skb_section(const char *sec)@@ -594,7 +594,7 @@ static bool unsupported_sk_skb_section(const char *sec)if (sec && sec[0] == '?')sec++;return sec && (strcmp(sec, "sk_skb") == 0 ||- strncmp(sec, "sk_skb/", 7) == 0);+ str_has_prefix(sec, "sk_skb/"));}static bool unsupported_socket_filter_section(const char *sec)@@ -603,8 +603,8 @@ static bool unsupported_socket_filter_section(const char *sec)sec++;return sec && (strcmp(sec, "socket") == 0 ||strcmp(sec, "socket_filter") == 0 ||- strncmp(sec, "socket/", 7) == 0 ||- strncmp(sec, "socket_filter/", 14) == 0);+ str_has_prefix(sec, "socket/") ||+ str_has_prefix(sec, "socket_filter/"));}static bool unsupported_cgroup_skb_section(const char *sec)@@ -618,7 +618,7 @@ static bool unsupported_cgroup_skb_section(const char *sec)return false;return strcmp(sec, "cgroup/skb") == 0 ||strcmp(sec, "cgroup_skb") == 0 ||- strncmp(sec, "cgroup_skb/", 11) == 0;+ str_has_prefix(sec, "cgroup_skb/");}static bool unsupported_fmod_ret_section(const char *sec)@@ -662,18 +662,21 @@ static __u32 attach_kind_from_section(const char *sec,const char **target){__u32 kind;+ size_t n;*target = NULL;if (!sec)return UPATCH_ATTACH_RAW_TRACEPOINT;if (sec[0] == '?')sec++;- if (strncmp(sec, "kprobe/", 7) == 0 && sec[7]) {- *target = sec + 7;+ n = str_has_prefix(sec, "kprobe/");+ if (n && sec[n]) {+ *target = sec + n;return UPATCH_ATTACH_KPROBE;}- if (strncmp(sec, "kretprobe/", 10) == 0 && sec[10]) {- *target = sec + 10;+ n = str_has_prefix(sec, "kretprobe/");+ if (n && sec[n]) {+ *target = sec + n;return UPATCH_ATTACH_KRETPROBE;}*target = uprobe_section_target(sec, &kind);@@ -683,14 +686,17 @@ static __u32 attach_kind_from_section(const char *sec,return UPATCH_ATTACH_CGROUP_SKB_INGRESS;if (strcmp(sec, "cgroup_skb/egress") == 0)return UPATCH_ATTACH_CGROUP_SKB_EGRESS;- if (strncmp(sec, "fmod_ret/", 9) == 0 && sec[9])+ n = str_has_prefix(sec, "fmod_ret/");+ if (n && sec[n])return UPATCH_ATTACH_FMOD_RET;- if (strncmp(sec, "fmod_ret.s/", 11) == 0 && sec[11])+ n = str_has_prefix(sec, "fmod_ret.s/");+ if (n && sec[n])return UPATCH_ATTACH_FMOD_RET;if (strcmp(sec, "netfilter") == 0)return UPATCH_ATTACH_NETFILTER_IPV6_PRE_ROUTING;- if (strncmp(sec, "xdp/", 4) == 0 && sec[4]) {- *target = sec + 4;+ n = str_has_prefix(sec, "xdp/");+ if (n && sec[n]) {+ *target = sec + n;return UPATCH_ATTACH_XDP;}return UPATCH_ATTACH_RAW_TRACEPOINT;@@ -1595,7 +1601,7 @@ static int set_target_attach_types(struct bpf_object *obj)type = BPF_CGROUP_INET_INGRESS;else if (strcmp(sec, "cgroup_skb/egress") == 0)type = BPF_CGROUP_INET_EGRESS;- else if (!strncmp(sec, "xdp/", 4)) {+ else if (str_has_prefix(sec, "xdp/")) {type = BPF_XDP;if (bpf_program__set_flags(p, bpf_program__flags(p) |BPF_F_XDP_HAS_FRAGS) != 0) {diff --git a/util/attest.c b/util/attest.cindex e5976e75..0c57d7b9 100644--- a/util/attest.c+++ b/util/attest.c@@ -741,6 +741,7 @@ int attest_verify(const char *evidence, size_t len,__u8 branch_written[32], branch_init[32], policy[32], bind[64];__u8 expected_name[TPM_NAME_LEN], pcr_expected[32];__u8 anchor_digest[32] = {}, cred[TPM_CREDENTIAL_LEN];+ const char *reg_index_hex;struct parse *p;size_t ak_public_len, nonce_len, attest_len;size_t cred_len = 0, i, runtime = 0;@@ -1048,10 +1049,11 @@ int attest_verify(const char *evidence, size_t len,if (ret == -EINVAL)goto out;crc = ret;+ reg_index_hex = p->reg_index;if (hex_decode(p->reg_name_hex, reg_name, TPM_NAME_LEN) ||hex_decode(p->reg_value_hex, reg_value, 32) ||- strncmp(p->reg_index, "0x", 2) ||- parse_x64(p->reg_index + 2, strlen(p->reg_index + 2), 0xffffffffULL,+ !str_skip_prefix(®_index_hex, "0x") ||+ parse_x64(reg_index_hex, strlen(reg_index_hex), 0xffffffffULL,®_index) ||p->reg_pcr < 0 || p->reg_pcr >= 24) {ret = -EINVAL;diff --git a/util/bpm_oci.c b/util/bpm_oci.cindex eb0088f8..970eadc8 100644--- a/util/bpm_oci.c+++ b/util/bpm_oci.c@@ -365,9 +365,9 @@ int bpm_oci_parse_endpoint(const char *endpoint, struct bpm_oci_client *c)const char *p, *ca_file, *scheme = getenv("BPM_OCI_SCHEME");char transport[16] = "https";- if (!endpoint || strncmp(endpoint, "oci://", 6) != 0)+ p = endpoint;+ if (!p || !str_skip_prefix(&p, "oci://"))return -EINVAL;- p = endpoint + 6;if (!*p || strchr(p, '/') || strchr(p, '?') || strchr(p, '#') || strchr(p, '@'))return -EINVAL;if (scheme && *scheme) {@@ -493,7 +493,7 @@ static int curl_once_ex(struct bpm_oci_client *c, const char *method,curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, follow ? 1L : 0L);if (follow) {const char *redirect_protocols =- !strncmp(c->base_url, "https://", 8) ? "https" : "http,https";+ str_has_prefix(c->base_url, "https://") ? "https" : "http,https";curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 5L);#if LIBCURL_VERSION_NUM >= 0x075500@@ -571,8 +571,7 @@ static int parse_challenge(const char *header, char *realm, size_t rsz,for (p = header + 6; *p;) {while (*p == ' ' || *p == ',')p++;- if (!strncmp(p, "realm=\"", 7)) {- p += 7;+ if (str_skip_prefix(&p, "realm=\"")) {q = strchr(p, '"');if (!q)return -EINVAL;@@ -581,8 +580,7 @@ static int parse_challenge(const char *header, char *realm, size_t rsz,memcpy(realm, p, q - p);realm[q - p] = 0;p = q + 1;- } else if (!strncmp(p, "service=\"", 9)) {- p += 9;+ } else if (str_skip_prefix(&p, "service=\"")) {q = strchr(p, '"');if (!q)return -EINVAL;@@ -591,8 +589,7 @@ static int parse_challenge(const char *header, char *realm, size_t rsz,memcpy(service, p, q - p);service[q - p] = 0;p = q + 1;- } else if (!strncmp(p, "scope=\"", 7)) {- p += 7;+ } else if (str_skip_prefix(&p, "scope=\"")) {q = strchr(p, '"');if (!q)return -EINVAL;@@ -697,8 +694,8 @@ static int get_bearer_token(struct bpm_oci_client *c, const char *challenge)* over no weaker a transport than the registry's own.*/curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR,- strncmp(c->base_url, "https://", 8) ? "http,https" :- "https");+ str_has_prefix(c->base_url, "https://") ? "https" :+ "http,https");curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);@@ -1047,9 +1044,9 @@ int bpm_oci_parse_pull_ref(const char *raw, struct bpm_oci_client *c,if (!raw || strlen(raw) >= sizeof(normalized))return -EINVAL;bpm_trim(raw, normalized, sizeof(normalized));- if (strncmp(normalized, "oci://", 6))+ p = normalized;+ if (!str_skip_prefix(&p, "oci://"))return -EINVAL;- p = normalized + 6;if (!*p || strchr(p, '@') || strchr(p, '?') || strchr(p, '#'))return -EINVAL;slash = strchr(p, '/');@@ -1059,13 +1056,12 @@ int bpm_oci_parse_pull_ref(const char *raw, struct bpm_oci_client *c,colon = strrchr(p, ':');if (!colon || colon <= last_slash || colon == last_slash + 1 || !colon[1])return -EINVAL;- if ((size_t)(slash - p) >= sizeof(endpoint) - 6 ||+ if ((size_t)(slash - normalized) >= sizeof(endpoint) ||(size_t)(colon - slash - 1) >= repository_sz ||strlen(colon + 1) >= tag_sz)return -ENAMETOOLONG;- memcpy(endpoint, "oci://", 6);- memcpy(endpoint + 6, p, slash - p);- endpoint[6 + (slash - p)] = '\0';+ memcpy(endpoint, normalized, slash - normalized);+ endpoint[slash - normalized] = '\0';memcpy(repository, slash + 1, colon - slash - 1);repository[colon - slash - 1] = '\0';bpm_copy_string(tag, tag_sz, colon + 1);@@ -1077,7 +1073,7 @@ int bpm_oci_parse_pull_ref(const char *raw, struct bpm_oci_client *c,if (!end)end = part + strlen(part);- if (end == part || (end - part == 2 && !strncmp(part, "..", 2)))+ if (end == part || span_equals(part, (size_t)(end - part), ".."))return -EINVAL;part = *end ? end + 1 : end;}@@ -1097,30 +1093,31 @@ int bpm_oci_parse_push_repo(const char *raw, struct bpm_oci_client *c,if (!raw || strlen(raw) >= sizeof(normalized))return -EINVAL;bpm_trim(raw, normalized, sizeof(normalized));- if (strncmp(normalized, "oci://", 6))+ p = normalized;+ if (!str_skip_prefix(&p, "oci://"))return -EINVAL;- p = normalized + 6;slash = strchr(p, '/');if (!*p || !slash || slash == p || !slash[1] || strchr(p, '@') ||strchr(p, '?') || strchr(p, '#'))return -EINVAL;- if ((size_t)(slash - p) >= sizeof(endpoint) - 6 ||+ if ((size_t)(slash - normalized) >= sizeof(endpoint) ||strlen(slash + 1) >= repository_sz)return -ENAMETOOLONG;- memcpy(endpoint, "oci://", 6);- memcpy(endpoint + 6, p, slash - p);- endpoint[6 + (slash - p)] = '\0';+ memcpy(endpoint, normalized, slash - normalized);+ endpoint[slash - normalized] = '\0';bpm_copy_string(repository, repository_sz, slash + 1);if (strchr(repository, ':') || strstr(repository, "//") ||strstr(repository, ".."))return -EINVAL;for (const char *part = repository; *part;) {const char *end = strchr(part, '/');+ size_t len;if (!end)end = part + strlen(part);- if (end == part || (end - part == 1 && part[0] == '.') ||- (end - part == 2 && !strncmp(part, "..", 2)))+ len = (size_t)(end - part);+ if (!len || span_equals(part, len, ".") ||+ span_equals(part, len, ".."))return -EINVAL;part = *end ? end + 1 : end;}@@ -1136,19 +1133,18 @@ int bpm_oci_parse_tree_repo(const char *raw, struct bpm_oci_client *c,char endpoint[BPM_MAX_ENDPOINT];const char *p, *slash;- if (!raw || strncmp(raw, "oci://", 6))+ p = raw;+ if (!p || !str_skip_prefix(&p, "oci://"))return -EINVAL;- p = raw + 6;slash = strchr(p, '/');if (!slash || slash == p || !slash[1] || strchr(p, '?') ||strchr(p, '#') || strchr(p, '@'))return -EINVAL;- if ((size_t)(slash - p) + 6 >= sizeof(endpoint) ||+ if ((size_t)(slash - raw) >= sizeof(endpoint) ||strlen(slash + 1) >= repository_sz)return -ENAMETOOLONG;- memcpy(endpoint, "oci://", 6);- memcpy(endpoint + 6, p, (size_t)(slash - p));- endpoint[6 + (size_t)(slash - p)] = '\0';+ memcpy(endpoint, raw, (size_t)(slash - raw));+ endpoint[slash - raw] = '\0';bpm_copy_string(repository, repository_sz, slash + 1);if (strstr(repository, "..") || strstr(repository, "//") ||strchr(repository, ':'))@@ -1214,8 +1210,8 @@ int bpm_sha256_digest(const void *data, size_t len, char *out, size_t out_sz)bool bpm_digest_matches(const char *want, const char *hex){- return want && !strncmp(want, "sha256:", 7) &&- !strcasecmp(want + 7, hex);+ return want && str_skip_prefix(&want, "sha256:") &&+ !strcasecmp(want, hex);}static int upload_location(const struct bpm_oci_client *c, const char *location,diff --git a/util/bpm_package.c b/util/bpm_package.cindex 091e0413..70175879 100644--- a/util/bpm_package.c+++ b/util/bpm_package.c@@ -325,6 +325,7 @@ static bool bpm_tar_header_ok(const __u8 h[512])bool bpm_archive_rel_ok(const char *name){const char *p = name, *q;+ size_t len;if (!name || !*name || *name == '/')return false;@@ -332,8 +333,8 @@ bool bpm_archive_rel_ok(const char *name)q = strchr(p, '/');if (!q)q = p + strlen(p);- if (q == p || (q - p == 1 && *p == '.') ||- (q - p == 2 && !strncmp(p, "..", 2)))+ len = (size_t)(q - p);+ if (!len || span_equals(p, len, ".") || span_equals(p, len, ".."))return false;p = *q ? q + 1 : q;}@@ -378,7 +379,7 @@ static bool package_member_name_ok(const char *name, const char *member)if (!bpm_archive_rel_ok(name) || !member)return false;slash = strchr(name, '/');- return slash && slash != name && strncmp(name, "./", 2) &&+ return slash && slash != name && !str_has_prefix(name, "./") &&bpm_archive_rel_ok(member) && !strcmp(slash + 1, member);}diff --git a/util/bpm_tree_state.c b/util/bpm_tree_state.cindex c351d5f5..e3fdc884 100644--- a/util/bpm_tree_state.c+++ b/util/bpm_tree_state.c@@ -214,8 +214,8 @@ static int selector_config_line(const char *line,if (!*start)return 0;- if (!strncmp(start, "# CONFIG_", 9)) {- start += 2;+ if (str_has_prefix(start, "# CONFIG_")) {+ start += strlen("# ");eq = strstr(start, " is not set");if (!eq)return 0;diff --git a/util/config.c b/util/config.cindex 8452745b..e5a2f274 100644--- a/util/config.c+++ b/util/config.c@@ -109,12 +109,12 @@ static void set_owner_auth(struct config *cfg, const char *val){size_t l;- if (strncmp(val, "hex:", 4) == 0) {+ if (str_skip_prefix(&val, "hex:")) {__u8 auth[sizeof(cfg->tpm_owner_auth)];size_t n;/* An ignored value must leave the one set before intact. */- if (!hex_decode_max(val + 4, auth, sizeof(auth), &n)) {+ if (!hex_decode_max(val, auth, sizeof(auth), &n)) {memcpy(cfg->tpm_owner_auth, auth, n);cfg->tpm_owner_auth_len = n;} else {@@ -247,13 +247,13 @@ static int config_parse(struct config *cfg, FILE *f,cfg->map_export_log_record_max_bytes = (__u32)v;elsecfg->map_export_otlp_max_bytes = (__u32)v;- } else if (!strncmp(key, "config.", 7) ||- !strncmp(key, "runtime.", 8)) {+ } else if (str_has_prefix(key, "config.") ||+ str_has_prefix(key, "runtime.")) {continue;} else {- if (strncmp(key, "map_export.", 11) == 0) {+ if (str_has_prefix(key, "map_export.")) {map_export_bad(cfg, key, val, "unknown key");- } else if (strncmp(key, "tls.", 4) == 0) {+ } else if (str_has_prefix(key, "tls.")) {cfg->tls_classical_hosts_valid = false;pr_warn("config: %s: unknown TLS setting", key);} else {diff --git a/util/elf_target.c b/util/elf_target.cindex 99987a4d..0f4e9b62 100644--- a/util/elf_target.c+++ b/util/elf_target.c@@ -47,10 +47,11 @@ static int note_build_id(Elf_Data *data,next = gelf_getnote(data, off, &nhdr, &name_off, &desc_off);if (!next)break;- if (nhdr.n_type == NT_GNU_BUILD_ID && nhdr.n_namesz == 4 &&+ if (nhdr.n_type == NT_GNU_BUILD_ID &&+ nhdr.n_namesz == sizeof("GNU") &&name_off <= data->d_size && nhdr.n_namesz <= data->d_size - name_off &&desc_off <= data->d_size && nhdr.n_descsz <= data->d_size - desc_off &&- memcmp(p + name_off, "GNU", 4) == 0) {+ !memcmp(p + name_off, "GNU", sizeof("GNU"))) {if (!nhdr.n_descsz ||nhdr.n_descsz > UPATCH_BUILD_ID_MAX)return -E2BIG;diff --git a/util/hex.c b/util/hex.cindex 0ddd4bf7..9dd21844 100644--- a/util/hex.c+++ b/util/hex.c@@ -6,6 +6,7 @@#include <shirudo/misc.h>#include <shirudo/overflow.h>+#include <shirudo/string.h>#include "hex.h"#include "malloc.h"@@ -85,9 +86,9 @@ int hex_decode_max(const char *hex, __u8 *out, size_t cap, size_t *len)int sha256_digest_decode(const char *digest, __u8 out[32]){- if (!digest || strncmp(digest, "sha256:", 7))+ if (!digest || !str_skip_prefix(&digest, "sha256:"))return -EINVAL;- return hex_decode(digest + 7, out, 32);+ return hex_decode(digest, out, 32);}void sha256_digest_encode(const __u8 in[32],diff --git a/util/image_bootstrap.c b/util/image_bootstrap.cindex 53a8cddb..4424e1de 100644--- a/util/image_bootstrap.c+++ b/util/image_bootstrap.c@@ -44,7 +44,7 @@ static int bootstrap_add_certificate(struct image_bootstrap *boot,{size_t i;- if (strncmp(path, RUNTIME_DIR "/", sizeof(RUNTIME_DIR)) ||+ if (!str_has_prefix(path, RUNTIME_DIR "/") ||!image_path_valid(path))return -EPERM;if (boot->n_certificates == KEYS_MAX)@@ -118,8 +118,8 @@ static int bootstrap_parse(FILE *file, struct image_bootstrap *boot,boot->pcr = pcr;boot->have_pcr = true;}- } else if (!strncmp(key, "config.", 7) ||- !strncmp(key, "runtime.", 8)) {+ } else if (str_has_prefix(key, "config.") ||+ str_has_prefix(key, "runtime.")) {ret = -EINVAL;}if (ret)diff --git a/util/image_cache.c b/util/image_cache.cindex 6bd28417..6405197b 100644--- a/util/image_cache.c+++ b/util/image_cache.c@@ -136,7 +136,7 @@ static int fetch_file(const char *source, const char *destination, __u64 max)ret = fsetxattr(fd, XATTR_SEAL, SEAL_LABEL,strlen(SEAL_LABEL), 0) ? -errno : 0;if (!ret)- ret = !strncmp(source, "https://", 8) ?+ ret = str_has_prefix(source, "https://") ?download_https(source, &download) :copy_local(source, &download);if (!ret && fsync(fd))diff --git a/util/image_config.c b/util/image_config.cindex cb603e85..de4662db 100644--- a/util/image_config.c+++ b/util/image_config.c@@ -196,7 +196,7 @@ static int validate_settings(int root_fd)ret = -EINVAL;break;}- } else if (strncmp(p, "map_export.", 11)) {+ } else if (!str_has_prefix(p, "map_export.")) {ret = -EPERM;break;}diff --git a/util/image_guards.c b/util/image_guards.cindex d999325a..2ea34ed9 100644--- a/util/image_guards.c+++ b/util/image_guards.c@@ -417,8 +417,10 @@ static int guard_link(const struct image_guard *guard,}if (*kernel_id != program.attach_btf_obj_id)return -EPROTO;- suffix = !strncmp(guard->prog, "shirudo_lsm_", 12) ?- guard->prog + 12 : guard->prog + 13;+ suffix = guard->prog;+ if (!str_skip_prefix(&suffix, "shirudo_lsm_") &&+ !str_skip_prefix(&suffix, "shirudo_seal_"))+ return -EPROTO;if (strsprintf(function, sizeof(function), "bpf_lsm_%s", suffix) < 0)return -ENAMETOOLONG;type_id = btf__find_by_name_kind(*kernel, function, BTF_KIND_FUNC);diff --git a/util/image_runtime.c b/util/image_runtime.cindex 5a3f726c..cc397591 100644--- a/util/image_runtime.c+++ b/util/image_runtime.c@@ -651,8 +651,7 @@ static int prepare_config(struct image_context *current,close_candidate();if (!trusted_boot)collect_mappings();- if (strncmp(target->prefix, IMAGE_CACHE_DIR "/",- sizeof(IMAGE_CACHE_DIR)) ||+ if (!str_has_prefix(target->prefix, IMAGE_CACHE_DIR "/") ||!image_path_valid(target->prefix))return -EPERM;ret = config_image_open(target->prefix, ¤t->candidate);@@ -1092,9 +1091,9 @@ int image_enter(const char *command, int argc, const char **argv)if (ret)return ret;for (int i = 1; i < argc; i++) {- if (!strncmp(argv[i], "--keys-dir", 10) ||- !strncmp(argv[i], "--cert", 6) ||- !strncmp(argv[i], "--tcti", 6))+ if (str_has_prefix(argv[i], "--keys-dir") ||+ str_has_prefix(argv[i], "--cert") ||+ str_has_prefix(argv[i], "--tcti"))return -EPERM;}if (!strcmp(command, "image"))diff --git a/util/kernel_build_id.c b/util/kernel_build_id.cindex b06d6fec..475c692a 100644--- a/util/kernel_build_id.c+++ b/util/kernel_build_id.c@@ -53,7 +53,8 @@ int kernel_build_id_from_notes(const void *notes, size_t notes_len,align4(descsz) > notes_len - desc_off)return -EINVAL;next = desc_off + align4(descsz);- if (type == 3 && namesz == 4 && !memcmp(p + name_off, "GNU", 4)) {+ if (type == 3 && namesz == sizeof("GNU") &&+ !memcmp(p + name_off, "GNU", sizeof("GNU"))) {if (!descsz || descsz > KERNEL_BUILD_ID_MAX)return -E2BIG;hex_encode(p + desc_off, descsz, out);diff --git a/util/sysinfo.c b/util/sysinfo.cindex 02415838..44a07da5 100644--- a/util/sysinfo.c+++ b/util/sysinfo.c@@ -227,6 +227,14 @@ static void kernel_config_entries_free(struct kernel_config_entry *entries,xfree(entries, cap * sizeof(*entries));}+/* CONFIG_ and a name after it. */+static bool config_name(const char *key)+{+ size_t n = str_has_prefix(key, "CONFIG_");++ return n && key[n];+}+int sysinfo_kernel_config_foreach(const char *kernel_release,shirudo_kernel_config_cb cb,void *ctx)@@ -252,10 +260,11 @@ int sysinfo_kernel_config_foreach(const char *kernel_release,if (!*key)continue;- if (strncmp(key, "# CONFIG_", 9) == 0) {- key += 2;+ if (str_has_prefix(key, "# CONFIG_")) {+ key += strlen("# ");not_set = strstr(key, " is not set");- if (!not_set || trim_config_text(not_set + 11)[0] != '\0')+ if (!not_set ||+ trim_config_text(not_set + strlen(" is not set"))[0] != '\0')continue;*not_set = '\0';value = unset;@@ -265,7 +274,7 @@ int sysinfo_kernel_config_foreach(const char *kernel_release,continue;*eq = '\0';key = trim_config_text(key);- if (strncmp(key, "CONFIG_", 7) != 0 || !key[7])+ if (!config_name(key))continue;value = trim_config_text(eq + 1);{@@ -277,7 +286,7 @@ int sysinfo_kernel_config_foreach(const char *kernel_release,}}}- if (strncmp(key, "CONFIG_", 7) != 0 || !key[7])+ if (!config_name(key))continue;if (n == cap) {struct kernel_config_entry *next;diff --git a/util/tpm.c b/util/tpm.cindex 6eba5804..ace134b8 100644--- a/util/tpm.c+++ b/util/tpm.c@@ -97,7 +97,7 @@ int tpm_tcti(char *buf, size_t size)tcti = cfg.tpm_tcti;if (!tcti || !*tcti)tcti = "device:/dev/tpmrm0";- if (image_config_active() && strncmp(tcti, "device:", 7))+ if (image_config_active() && !str_has_prefix(tcti, "device:"))return -EACCES;n = strscpy(buf, tcti, size);return n < 0 ? (int)n : 0;diff --git a/util/upatch_maps_otel.c b/util/upatch_maps_otel.cindex 1eb4d4b3..32bc255a 100644--- a/util/upatch_maps_otel.c+++ b/util/upatch_maps_otel.c@@ -1665,9 +1665,9 @@ static int parse_s3_spec(struct otel_s3_state *st, const char *spec)const char *access, *secret;size_t bucket_len, prefix_len, credentials_len;- if (!spec || strncmp(spec, "s3://", 5) != 0)+ bucket = spec;+ if (!bucket || !str_skip_prefix(&bucket, "s3://"))return -EINVAL;- bucket = spec + 5;slash = strchr(bucket, '/');bucket_len = slash ? (size_t)(slash - bucket) : strlen(bucket);if (!valid_bucket(bucket, bucket_len))diff --git a/util/upatch_resolve.c b/util/upatch_resolve.cindex af592872..d72d98de 100644--- a/util/upatch_resolve.c+++ b/util/upatch_resolve.c@@ -317,9 +317,8 @@ int upatch_resolve_location(struct btf *vbtf, const char *name,prefix = "?";/* Strip the bpf_lsm_ prefix the kernel mangles LSM hooks with. */- if (info.type == BPF_PROG_TYPE_LSM && attach_name &&- strncmp(attach_name, "bpf_lsm_", 8) == 0)- attach_name += 8;+ if (info.type == BPF_PROG_TYPE_LSM && attach_name)+ attach_name += str_has_prefix(attach_name, "bpf_lsm_");if (attach_name && *attach_name)return strsprintf(out, cap, "%s/%s", prefix, attach_name) < 0 ?