eBPF-based security platform
treewide: walk tokens with for_each_token(), not strtok_r()
Daniel Borkmann4ce8b5e3ac2e
diff --git a/testing/proofs/cbmc/bpm-beefile-tables.c b/testing/proofs/cbmc/bpm-beefile-tables.cindex befb93d2..0bb07df6 100644--- a/testing/proofs/cbmc/bpm-beefile-tables.c+++ b/testing/proofs/cbmc/bpm-beefile-tables.c@@ -37,28 +37,6 @@ enum {static struct bpm_build_spec spec;-/* strtok_r() for the one delimiter the reader cuts lines at. */-char *strtok_r(char *s, const char *delim, char **save)-{- char *end;-- __CPROVER_assert(delim[0] && !delim[1], "one delimiter");- if (!s)- s = *save;- while (*s == delim[0])- s++;- if (!*s) {- *save = s;- return NULL;- }- for (end = s; *end && *end != delim[0]; end++)- ;- if (*end)- *end++ = '\0';- *save = end;- return s;-}-/* The tables of an upatch, which the reader allocates at their limits. */void *xcalloc(size_t nmemb, size_t size){diff --git a/testing/proofs/cbmc/bpm-tree-state-replay.c b/testing/proofs/cbmc/bpm-tree-state-replay.cindex 9f5d6ee8..9ada909a 100644--- a/testing/proofs/cbmc/bpm-tree-state-replay.c+++ b/testing/proofs/cbmc/bpm-tree-state-replay.c@@ -9,12 +9,16 @@* file for the bytes of the log. JSON, hex and SHA-256 are stubs.*/+/* util/string.c is included behind a file that includes its header. */+#define STRING_INTERNAL+#include "proof.h"#include "../../../util/bpm_tree_state.c"/* lines_len() as the code has it; the file comes from the stub below. */#define read_file read_file_unused#include "../../../util/io.c"#undef read_file+#include "../../../util/string.c"#ifdef TREE_REPLAY_LINES/* Each line is a byte and its newline at least. */@@ -40,28 +44,6 @@ static int n_lines;static char original[LOG_LEN + 1], log_body[LOG_LEN + 1];static int read_error, hash_error, n_freed;-/* CBMC has no strtok_r(); glibc's, with strspn() and strcspn() as loops. */-char *strtok_r(char *s, const char *delim, char **save)-{- char *token;-- if (!s)- s = *save;- while (*s && strchr(delim, *s))- s++;- if (!*s) {- *save = s;- return NULL;- }- token = s;- while (*s && !strchr(delim, *s))- s++;- if (*s)- *s++ = '\0';- *save = s;- return token;-}-/** The log lies in a buffer of the harness, filled before anything can* fail: CBMC follows the bytes of a line as constants only when no@@ -112,7 +94,7 @@ int json_parse(const char *data, size_t len, struct json_field *f, size_t n)f[1].type == JSON_T_STRING && f[1].dst_cap == 128 &&f[2].type == JSON_T_STRING && f[2].dst_cap == 65,"a line's three fields, each with its room");- __CPROVER_assert(len == strlen(data), "a line is parsed whole");+ __CPROVER_assert(len && data[len] == '\n', "a line is parsed whole");line_at[n_lines] = (size_t)(data - log_body);line_len[n_lines] = len;r = &records[n_lines++];diff --git a/testing/proofs/cbmc/dm-names.c b/testing/proofs/cbmc/dm-names.cindex 2d410bd0..e2275250 100644--- a/testing/proofs/cbmc/dm-names.c+++ b/testing/proofs/cbmc/dm-names.c@@ -6,7 +6,7 @@* LEN_MAX bytes, and on names of 127 and 128 bytes that end in letters: a* device-mapper name is exactly 1 to 127 of [A-Za-z0-9._-] and not "." or* "..", and a device is two decimal numbers around a ':' that the device- * number holds unchanged.+ * number holds unchanged, read from the bytes of its token alone.*/#define PROOF_DEVICE_NUMBERS@@ -72,21 +72,22 @@ static void long_name(size_t len)void harness(void){- char *name = any_string(), *token = any_string(), *was;- size_t n = strlen(name), colon;+ size_t n, len, colon;+ char *name = any_string();+ struct dm_token token;dev_t dev;+ n = strlen(name);__CPROVER_assert(dm_name_ok(name) == name_valid(name, n),"1 to 127 of [A-Za-z0-9._-], not . or ..");long_name(DM_NAME_LEN);long_name(DM_NAME_LEN + 1);- n = strlen(token);- was = any_bytes(n + 1);- memcpy(was, token, n + 1);- if (dm_device(token, &dev))+ __CPROVER_assume(len <= LEN_MAX);+ token = (struct dm_token){ any_input(len, LEN_MAX), len };+ if (dm_device(&token, &dev))return;- colon = strchr(was, ':') - was;- __CPROVER_assert(decimal(was, colon) &&- decimal(was + colon + 1, n - colon - 1),+ colon = (size_t)((const char *)memchr(token.s, ':', len) - token.s);+ __CPROVER_assert(decimal(token.s, colon) &&+ decimal(token.s + colon + 1, len - colon - 1),"decimal major:minor");}diff --git a/testing/proofs/lean4/Shirudo/ArchivePath.lean b/testing/proofs/lean4/Shirudo/ArchivePath.leanindex ad6bb73e..729f11b3 100644--- a/testing/proofs/lean4/Shirudo/ArchivePath.lean+++ b/testing/proofs/lean4/Shirudo/ArchivePath.lean@@ -19,8 +19,8 @@ into the components between its slashes, one that starts with `/` startsat the filesystem root, a final `/` names the directory before it, `.`stays, `..` goes up, except at the filesystem root, and any othercomponent goes down. An empty component is refused, where the kernel and-the `strtok_r()` walk of util/seal.c skip it; no name the check takes-holds one. A directory is the list of its components from the+the `for_each_token()` walk of util/seal.c skip it; no name the check+takes holds one. A directory is the list of its components from thefilesystem root. util/seal.c walks every component with `O_NOFOLLOW`, sono symbolic link is followed, and the archive can create none.diff --git a/tools/shirudo-build/bpm-build.c b/tools/shirudo-build/bpm-build.cindex 71dd002b..8d831882 100644--- a/tools/shirudo-build/bpm-build.c+++ b/tools/shirudo-build/bpm-build.c@@ -449,13 +449,14 @@ static int build_parse_spec(struct bpm_build_spec *spec, char *body)struct bpm_build_file *file = NULL;struct tree_selector *sel = NULL;bool tree_section = false;- char *save = NULL, *line;char section[48] = {};+ size_t line_len;+ char *line;- for (line = strtok_r(body, "\n", &save); line;- line = strtok_r(NULL, "\n", &save)) {+ for_each_token(line, line_len, body, strlen(body), "\n") {char *s, *eq, *key, *value;+ line[line_len] = '\0';build_strip_comment(line);s = build_trim(line);if (!*s)diff --git a/tools/shirudo-build/compile.c b/tools/shirudo-build/compile.cindex af78e27c..185a1f45 100644--- a/tools/shirudo-build/compile.c+++ b/tools/shirudo-build/compile.c@@ -158,13 +158,14 @@ int build_compile(const char *source, const char *output,push(argv, &n, output);if (extra_cflags && extra_cflags[0]) {- char *tok, *save;+ size_t len;+ char *tok;cf_copy = xstrdup(extra_cflags);if (!cf_copy)return -ENOMEM;- for (tok = strtok_r(cf_copy, " \t\n", &save); tok;- tok = strtok_r(NULL, " \t\n", &save)) {+ for_each_token(tok, len, cf_copy, strlen(cf_copy), " \t\n") {+ tok[len] = '\0';ret = push(argv, &n, tok);if (ret) {xstrfree(cf_copy);diff --git a/util/bpm_tree_state.c b/util/bpm_tree_state.cindex 3591cf8d..84f3b1fc 100644--- a/util/bpm_tree_state.c+++ b/util/bpm_tree_state.c@@ -690,8 +690,8 @@ int tree_event_append(__s64 seq, const char *operation_digest,int tree_event_replay(__u8 out[32]){__u8 *body;- size_t len;- char *save, *line;+ size_t len, line_len;+ const char *line;__u8 chain[32] = {};__s64 previous_seq = 0;int ret = tree_read_file(BPM_TREE_EVENTLOG_PATH, &body, &len);@@ -704,8 +704,8 @@ int tree_event_replay(__u8 out[32])return -EINVAL;}body[lines_len((const char *)body, len)] = '\0';- for (line = strtok_r((char *)body, "\n", &save); line;- line = strtok_r(NULL, "\n", &save)) {+ for_each_token(line, line_len, (const char *)body,+ strlen((const char *)body), "\n") {char digest[128] = {};char projection[65] = {};__s64 seq = 0;@@ -718,7 +718,7 @@ int tree_event_replay(__u8 out[32])};__u8 d[32], next[64], recorded[32];- ret = json_parse(line, strlen(line), f, ARRAY_SIZE(f));+ ret = json_parse(line, line_len, f, ARRAY_SIZE(f));if (ret || !f[0].seen || !f[1].seen || !f[2].seen ||seq <= previous_seq || strlen(projection) != 64 ||hex_decode(projection, recorded, 32)) {diff --git a/util/dm_verity.c b/util/dm_verity.cindex 5f7d5355..ea667978 100644--- a/util/dm_verity.c+++ b/util/dm_verity.c@@ -213,24 +213,28 @@ static int device_path(struct dm_verity *device, __u64 dev): -ESTALE;}-static int dm_number(const char *token, __u64 *out)+/* A parameter of a target's table, in the reply it is part of. */+struct dm_token {+ const char *s;+ size_t len;+};++static int dm_number(const char *s, size_t len, __u64 *out){- if (!token)- return -EINVAL;- return parse_u64(token, strlen(token), ~0ULL, out) ? -EINVAL : 0;+ return parse_u64(s, len, ~0ULL, out) ? -EINVAL : 0;}-static int dm_device(char *token, dev_t *out)+static int dm_device(const struct dm_token *token, dev_t *out){+ const char *separator = memchr(token->s, ':', token->len);__u64 major_nr, minor_nr;- char *separator;+ size_t major_len;- separator = strchr(token, ':');if (!separator)return -EINVAL;- *separator = '\0';- if (dm_number(token, &major_nr) ||- dm_number(separator + 1, &minor_nr) ||+ major_len = (size_t)(separator - token->s);+ if (dm_number(token->s, major_len, &major_nr) ||+ dm_number(separator + 1, token->len - major_len - 1, &minor_nr) ||major_nr > UINT_MAX || minor_nr > UINT_MAX)return -EINVAL;*out = makedev(major_nr, minor_nr);@@ -241,12 +245,13 @@ static int check_table(union dm_buffer *buf,const struct config_image *image,struct dm_verity *device){- char root[65], salt[65], *tokens[13], *save = NULL, *token;struct dm_target_spec *target;- __u64 value;- size_t offset, avail;+ struct dm_token tokens[13];+ size_t offset, avail, len;+ char root[65], salt[65];+ const char *params, *s;__u32 count = 0, i;- char *params;+ __u64 value;if (!(buf->io.flags & DM_READONLY_FLAG) ||buf->io.flags & (DM_SUSPEND_FLAG | DM_INACTIVE_PRESENT_FLAG) ||@@ -265,28 +270,30 @@ static int check_table(union dm_buffer *buf,strnlen(target->target_type,sizeof(target->target_type)), "verity"))return -EKEYREJECTED;- params = (char *)(target + 1);+ params = (const char *)(target + 1);avail = buf->io.data_size - offset - sizeof(*target);if (!memchr(params, 0, avail))return -EINVAL;- for (token = strtok_r(params, " ", &save); token;- token = strtok_r(NULL, " ", &save)) {- if (count == 13)+ for_each_token(s, len, params, strlen(params), " ") {+ if (count == ARRAY_SIZE(tokens))return -EKEYREJECTED;- tokens[count++] = token;+ tokens[count++] = (struct dm_token){ s, len };}if (image->signed_root) {- if (count != 13 || strcmp(tokens[10], "2") ||- strcmp(tokens[11], "root_hash_sig_key_desc"))+ if (count != 13 ||+ !span_equals(tokens[10].s, tokens[10].len, "2") ||+ !span_equals(tokens[11].s, tokens[11].len,+ "root_hash_sig_key_desc"))return -EKEYREJECTED;} else if ((count != 10 && count != 11) ||- (count == 11 && strcmp(tokens[10], "0"))) {+ (count == 11 &&+ !span_equals(tokens[10].s, tokens[10].len, "0"))) {return -EKEYREJECTED;}for (i = 0; i < 7; i++) {if (i == 1 || i == 2)continue;- if (dm_number(tokens[i], &value))+ if (dm_number(tokens[i].s, tokens[i].len, &value))return -EINVAL;if ((i == 0 && value != 1) ||((i == 3 || i == 4) &&@@ -297,11 +304,12 @@ static int check_table(union dm_buffer *buf,}hex_encode(image->root_hash, 32, root);hex_encode(image->salt, 32, salt);- if (strcmp(tokens[7], "sha256") || strcmp(tokens[8], root) ||- strcmp(tokens[9], salt))+ if (!span_equals(tokens[7].s, tokens[7].len, "sha256") ||+ !span_equals_str(tokens[8].s, tokens[8].len, root) ||+ !span_equals_str(tokens[9].s, tokens[9].len, salt))return -EKEYREJECTED;- if (dm_device(tokens[1], &device->data_device) ||- dm_device(tokens[2], &device->hash_device))+ if (dm_device(&tokens[1], &device->data_device) ||+ dm_device(&tokens[2], &device->hash_device))return -EINVAL;return 0;}diff --git a/util/eventlog.c b/util/eventlog.cindex 5ac93869..32351f72 100644--- a/util/eventlog.c+++ b/util/eventlog.c@@ -72,16 +72,21 @@ int eventlog_append(const char *json_line)* log failing on it, so appenders take the lock that keeps them from* interleaving and append_line() drops what did not finish.*/-int eventlog_append_to(const char *path, const char *json_line)+static int append_record(const char *path, const char *line, size_t len){int ret;- ret = seal_append_line(path, json_line, strlen(json_line));+ ret = seal_append_line(path, line, len);if (ret)pr_err("eventlog: append to %s: %s", path, strerror(-ret));return ret;}+int eventlog_append_to(const char *path, const char *json_line)+{+ return append_record(path, json_line, strlen(json_line));+}+int eventlog_would_exceed(__u64 max_bytes){struct stat st;@@ -188,18 +193,18 @@ out:* This boot's records from its last init line on; the callback learns* which line that is so a replay can start from zero.*/-static int walk_lines(char *buf, bool all,+static int walk_lines(const char *buf, bool all,int (*cb)(const char *line, size_t len, bool is_init,void *ctx), void *ctx){char boot_id[64], line_boot[64], type[32];bool in_boot = false;- char *line, *save;+ const char *line;int ret = 0;+ size_t len;eventlog_boot_id(boot_id, sizeof(boot_id));- for (line = strtok_r(buf, "\n", &save); line && !ret;- line = strtok_r(NULL, "\n", &save)) {+ for_each_token(line, len, buf, strlen(buf), "\n") {struct json_field f[] = {{ "boot_id", JSON_T_STRING, line_boot,sizeof(line_boot), 0, NULL, 0 },@@ -210,7 +215,7 @@ static int walk_lines(char *buf, bool all,line_boot[0] = '\0';type[0] = '\0';- if (json_parse(line, strlen(line), f, 2)) {+ if (json_parse(line, len, f, 2)) {ret = -EINVAL;break;}@@ -222,7 +227,9 @@ static int walk_lines(char *buf, bool all,in_boot = true;if (!all && !in_boot)continue;- ret = cb(line, strlen(line), is_init, ctx);+ ret = cb(line, len, is_init, ctx);+ if (ret)+ break;}if (!all && !ret && !in_boot)return -ENOENT;@@ -287,10 +294,27 @@ static int log_holds(const char *line, size_t len)return a.found ? 1 : 0;}+/* Append each of the pending records the log does not hold yet. */+static int adopt_records(const char *records)+{+ const char *line;+ size_t len;+ int ret;++ for_each_token(line, len, records, strlen(records), "\n") {+ ret = log_holds(line, len);+ if (!ret)+ ret = append_record(eventlog_path(), line, len);+ if (ret < 0)+ return ret;+ }+ return 0;+}+static int adopt_pending(void){const char *pending = eventlog_pending_path();- char *buf = NULL, *line, *save;+ char *buf = NULL;size_t len = 0;int ret;@@ -300,19 +324,8 @@ static int adopt_pending(void)if (ret)return ret;ret = log_records(buf, len);- for (line = strtok_r(buf, "\n", &save); line && !ret;- line = strtok_r(NULL, "\n", &save)) {- if (!*line)- continue;- ret = log_holds(line, strlen(line));- if (ret > 0) {- ret = 0;- continue;- }- if (!ret)- ret = eventlog_append_to(eventlog_path(),- line);- }+ if (!ret)+ ret = adopt_records(buf);xfree(buf, len + 1);if (ret)return ret;diff --git a/util/preflight.c b/util/preflight.cindex 2c1dd664..a8524084 100644--- a/util/preflight.c+++ b/util/preflight.c@@ -90,22 +90,21 @@ static void check_root(struct preflight_result *r)static bool lsm_lists_bpf(void){- char buf[1024], *save;+ const char *name;+ char buf[1024];+ size_t len;ssize_t n;int fd;fd = open("/sys/kernel/security/lsm", O_RDONLY | O_CLOEXEC);if (fd < 0)return false;- n = read(fd, buf, sizeof(buf) - 1);+ n = read(fd, buf, sizeof(buf));close(fd);if (n <= 0)return false;- buf[n] = '\0';-- for (char *p = strtok_r(buf, ",\n", &save); p;- p = strtok_r(NULL, ",\n", &save)) {- if (strcmp(p, "bpf") == 0)+ for_each_token(name, len, buf, (size_t)n, ",\n") {+ if (span_equals(name, len, "bpf"))return true;}return false;diff --git a/util/seal.c b/util/seal.cindex 398b5d95..ab4a9ddc 100644--- a/util/seal.c+++ b/util/seal.c@@ -230,18 +230,21 @@ static int seal_same(int dfd, int fd)*/static int seal_open_dir(const char *path, bool create, mode_t mode){- char buf[PATH_MAX], *comp, *save;+ char buf[PATH_MAX], *comp;int dfd, nfd, ret = 0;bool created;+ ssize_t len;+ size_t n;- if (strscpy(buf, path, sizeof(buf)) < 0)+ len = strscpy(buf, path, sizeof(buf));+ if (len < 0)return -ENAMETOOLONG;dfd = open(buf[0] == '/' ? "/" : ".",O_RDONLY | O_DIRECTORY | O_CLOEXEC);if (dfd < 0)return -errno;- for (comp = strtok_r(buf, "/", &save); comp;- comp = strtok_r(NULL, "/", &save)) {+ for_each_token(comp, n, buf, (size_t)len, "/") {+ comp[n] = '\0';created = create && mkdirat(dfd, comp, mode) == 0;if (create && !created && errno != EEXIST) {ret = -errno;diff --git a/util/upatch_maps_otel.c b/util/upatch_maps_otel.cindex dafc633a..57987698 100644--- a/util/upatch_maps_otel.c+++ b/util/upatch_maps_otel.c@@ -830,9 +830,9 @@ static bool header_value_ok(const char *s)static int add_configured_headers(struct otel_state *st, const char *input){- char *copy, *save = NULL, *pair;- size_t total = input ? strlen(input) : 0;+ size_t total = input ? strlen(input) : 0, pair_len;bool tenant_seen = false;+ char *copy, *pair;int ret = 0;if (!input)@@ -842,14 +842,14 @@ static int add_configured_headers(struct otel_state *st, const char *input)copy = xstrdup(input);if (!copy)return -ENOMEM;- for (pair = strtok_r(copy, ",", &save); pair;- pair = strtok_r(NULL, ",", &save)) {- char *eq = strchr(pair, '=');- char *name, *value, *line;+ for_each_token(pair, pair_len, copy, total, ",") {+ char *name, *value, *line, *eq;const char *header;bool tenant;size_t n;+ pair[pair_len] = '\0';+ eq = strchr(pair, '=');if (!eq) {ret = -EINVAL;break;