diff --git a/README.md b/README.md index 9a22383..03c2d00 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,7 @@ where the line runs and how to add another one. docs/PLUGINS.md the ABI, the threading rules docs/PROTOCOL.md the line protocol a GUI client speaks docs/GATEWAY.md the OpenAI endpoint and its two tool sets + docs/TOOL-ROOT.md the tools_root fence: what it holds and what not tests/ the test binaries, run by `make check` docs/splinter.1 manual page src/www/index*.html the site, written by hand (de, en, pt_BR) @@ -1061,6 +1062,13 @@ ABI in `docs/PLUGINS.md`. ## Limits, stated - Tool arguments reach the tool as one string; each tool validates its own. +- The file tools (`read`, `write`, `edit`, `search`, `list`) are only fenced in + when `tools_root` is set; empty is the default and means no boundary, so a + model that can mutate can also write `~/.ssh/authorized_keys`. With a root set, + every path is resolved before it is used (`..`, symlinks, and the entries a + recursive `search` walks), so a link inside the root cannot lead out of it. + `run` cannot be fenced at all — a shell opens any path — it only starts in the + root. - MCP tools are all `mutate`, so they ask before they run. - The ring only retries on rate limits; a 500 from a broken endpoint also counts as pressure, so a provider that fails hard gets skipped rather than fixed. diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 593133a..a7ebcec 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -239,10 +239,10 @@ lies about what it does. ## Keys -A setting that names a path (`session_dir`, `state_dir`, `skills_dir`) takes a -leading `~` as the home directory, exactly as the shipped template writes it: -`~/src` is `$HOME/src`. Any other path is used verbatim. The `${NAME}` form -inserts an environment variable. +A setting that names a path (`session_dir`, `state_dir`, `tools_root`, +`skills_dir`) takes a leading `~` as the home directory, exactly as the shipped +template writes it: `~/src` is `$HOME/src`. Any other path is used verbatim. +The `${NAME}` form inserts an environment variable. | key | meaning | |-----|---------| @@ -267,6 +267,7 @@ inserts an environment variable. | `embed_key_env` | env var holding the key for `embed_endpoint` | | `embed_timeout` | seconds one embedding request may take | | `session_dir` | where session logs go (default `~/.splinter`); `SPLINTER_SESSION_DIR` overrides it, which is how `make check` keeps its test sessions out of yours | +| `tools_root` | the only directory the file tools (`read`, `write`, `edit`, `search`, `list`) may touch. Empty — the default — means no boundary, so an existing setup keeps working. `run` is not fenced by it (a shell can open any path); it starts there. Resolved once at startup with `realpath`, so `..` and symlinks are checked against the file that is actually reached, and a root that does not exist is refused at startup instead of matching nothing | | `system_prompt` | sent once at the start of a conversation | | `telegram_allow` | user ids the gateway answers, comma-separated; empty means nobody | | `skills_dir` | a directory of skills, one line each | @@ -466,6 +467,7 @@ plugin = lcm plugin = cps plugin = clock session_dir = /home/lotherk/.splinter +tools_root = /home/lotherk/src # the file tools stay here; omit for none ``` ## Example: Claude Code as the model diff --git a/docs/TOOL-ROOT.md b/docs/TOOL-ROOT.md new file mode 100644 index 0000000..8c60c70 --- /dev/null +++ b/docs/TOOL-ROOT.md @@ -0,0 +1,40 @@ +# The tool root: what it is and what it is not + +The file tools (`read`, `write`, `edit`, `search`, `list`) act with the rights of +the splinter process. Without a boundary, a model with mutate rights - or a +prompt-injected one - can write `~/.ssh/authorized_keys`, `~/.splinter/splinter.conf` +(which names the plugins the harness loads), `~/.bashrc`. The authorization +classes say *whether* a tool may run, never *where*. + +`tools_root` in `core { }` closes that: + +``` +core { + tools_root = ~/src # empty (the default) = no boundary +} +``` + +Rules that make it hold: + +- **Resolve before deciding, then use the resolved path.** A check on one string + and a write to another is the whole class of bug this exists to prevent. + `realpath()` for existing paths; `resolve_target()` for a path that does not + exist yet, so a *dangling* symlink inside the root cannot be followed out of it + by the write that creates the target. +- **Recursion needs the same check as the argument.** `search` walks + directories; `stat()` follows a directory symlink. Every entry is resolved + before it is opened, otherwise a link inside the root is a door. +- **The root is resolved once at startup.** A symlinked root would make a later + comparison lie, and a root that does not exist is refused at startup with the + path in the message instead of silently matching nothing. +- **`run` is not fenced and cannot be.** A shell opens any path it likes. It + starts in the root (convenience), and when that `chdir` fails the failure goes + into the tool's observation - after the redirection, so the model reads it as + part of what happened, not on the operator's terminal. +- **Empty means off.** Anything else would be a change to a working setup + disguised as a fix. + +Tests that guard it live in `tests/test_builtin.c` (absolute path outside, +`../..` walk, symlink inside pointing out, dangling symlink, directory symlink +through `search`, and the same tree still readable inside the root). Each was +verified by removing the check and watching the test go red. diff --git a/include/splinter.h b/include/splinter.h index 036934d..f482295 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -496,7 +496,7 @@ int sp_agent_resume(struct sp_agent *, int decision, struct sp_buf *answer, struct sp_buf *err); /* builtin.c */ -int sp_builtin_register(struct sp_registry *); +int sp_builtin_register(struct sp_registry *, const char *root); /* * Environment names the 'run' tool's shell does not inherit (API keys, * tokens). A trailing '*' makes a prefix. sp_secret_env_is takes "NAME=value". diff --git a/src/backend/builtin.c b/src/backend/builtin.c index 5c1fa72..18c8242 100644 --- a/src/backend/builtin.c +++ b/src/backend/builtin.c @@ -9,6 +9,8 @@ * Shell execution goes through popen("/bin/sh -c") and its exit status is * reported; a command that fails is an observation, not an exception. */ +#define _XOPEN_SOURCE 700 /* realpath() for the tool root */ + #include #include #include @@ -126,6 +128,35 @@ sp_secret_env_is(const char *entry) extern char **environ; +#define TOOL_ROOT_MAX 1024 + +/* + * The boundary the file tools stay inside, when the operator set one. + * + * Without it a model with mutate rights can write anything the process can: + * ~/.ssh/authorized_keys, ~/.splinter/splinter.conf (which names the plugins + * this harness loads), ~/.bashrc. The authorization classes say *whether* a + * tool may run, not *where* it may look - and a prompt-injected model has the + * same rights as a careful one. + * + * Empty root means no boundary, which is the default: a setup that works today + * must keep working. `run` is not covered by this and cannot be - a shell can + * open any path it likes; it gets the root as its working directory, which is a + * convenience, not a fence. + * + * One struct per tool, because the registry's dispose callback frees it and a + * shared pointer would be freed once per tool. It lives up here because + * tool_run() - further down - already needs to know whether a root is set. + */ +struct tool_root { + int on; + char root[TOOL_ROOT_MAX]; /* canonical: realpath at registration */ +}; + +static int count_lines(const char *s, size_t upto); +static int resolve_target(const char *path, char *out, size_t cap); +static char *slurp(const char *path, size_t *lenp, struct sp_buf *err); + #define RUN_MAX_OUTPUT (1u << 20) #define RUN_TIMEOUT_S 600 @@ -156,7 +187,6 @@ tool_run(const char *args, struct sp_buf *out, void *ctx) pid_t child; time_t end; - (void)ctx; if (sp_buf_init(&keep) != 0) return -1; cmd = arg_text(args, "command", &keep); @@ -198,6 +228,11 @@ tool_run(const char *args, struct sp_buf *out, void *ctx) int dn = open("/dev/null", O_RDONLY); (void)setpgid(0, 0); + /* + * The root is not a fence for a shell - a child that wants to + * leave it can. It is where the command starts, so a relative + * path means what the operator meant. + */ if (dn >= 0) { (void)dup2(dn, STDIN_FILENO); if (dn != STDIN_FILENO) @@ -205,6 +240,24 @@ tool_run(const char *args, struct sp_buf *out, void *ctx) } (void)dup2(fds[1], STDOUT_FILENO); (void)dup2(fds[1], STDERR_FILENO); + /* + * After the redirection, so the model reads it as part of the + * observation: a command that ran in another directory than the + * one it named must not look like it ran where it was told. Not + * exit 127 either - that reads as "no such command". + */ + if (ctx != NULL && ((const struct tool_root *)ctx)->on && + chdir(((const struct tool_root *)ctx)->root) != 0) { + static const char msg[] = + "splinter: cannot enter the tool root: "; + const char *why = strerror(errno); + + /* sizeof - 1, never a counted number: a length typed by + * hand is how half a message gets written. */ + (void)write(STDERR_FILENO, msg, sizeof(msg) - 1); + (void)write(STDERR_FILENO, why, strlen(why)); + (void)write(STDERR_FILENO, "\n", 1); + } close(fds[0]); close(fds[1]); execle("/bin/sh", "sh", "-c", cmd, (char *)NULL, envp); @@ -298,8 +351,149 @@ tool_run(const char *args, struct sp_buf *out, void *ctx) #define TOOL_MAX_FILE (4 * 1024 * 1024) #define TOOL_MAX_HITS 100 -static int count_lines(const char *s, size_t upto); -static char *slurp(const char *path, size_t *lenp, struct sp_buf *err); +static void +tool_root_free(struct sp_tool *t) +{ + free(t->ctx); + t->ctx = NULL; +} + +static struct tool_root * +tool_root_new(const char *root) +{ + struct tool_root *tr; + char real[TOOL_ROOT_MAX]; + + tr = calloc(1, sizeof(*tr)); + if (tr == NULL) + return NULL; + if (root == NULL || *root == '\0') + return tr; /* off: every path is allowed */ + /* + * The root is resolved once, at startup, so a symlinked root cannot make + * the comparison lie, and a root that does not exist is an error the + * operator sees instead of a fence that silently matches nothing. + */ + if (realpath(root, real) == NULL) { + free(tr); + return NULL; + } + tr->on = 1; + snprintf(tr->root, sizeof(tr->root), "%s", real); + return tr; +} + +static int +under_root(const struct tool_root *tr, const char *real) +{ + size_t n; + + if (tr == NULL || !tr->on) + return 1; + if (strcmp(tr->root, "/") == 0) + return real[0] == '/'; + n = strlen(tr->root); + if (strncmp(real, tr->root, n) != 0) + return 0; + /* "/root" matches "/root" and "/root/x", never "/rootfs" */ + return real[n] == '\0' || real[n] == '/'; +} + +/* + * Is 'path' inside the root? 1 allowed, 0 refused. + * + * realpath() does the work: it resolves "..", "." and every symlink on the way, + * so a link inside the root that points at /etc/passwd is refused for pointing + * there - checking the string the model sent would say "inside". + * + * A path that does not exist yet (a write creating a file) cannot be resolved; + * its directory can, and that is what decides. The last component is then taken + * as given, which is safe: it is a name in a directory the root covers, and a + * name that already is a symlink would have resolved above. + * + * 'resolved' (optional) gets the canonical path, which is what the tool then + * uses: a check on one string and a write to another is the whole class of bug + * this function exists to prevent. + */ +static int +path_checked(const struct tool_root *tr, const char *path, char *resolved, + size_t cap, struct sp_buf *err) +{ + char full[TOOL_ROOT_MAX], dir[TOOL_ROOT_MAX]; + char dirreal[TOOL_ROOT_MAX], real[TOOL_ROOT_MAX]; + char target[TOOL_ROOT_MAX]; + const char *base; + char *slash; + size_t n, base_len; + + if (path == NULL || *path == '\0') + return 1; /* the caller reports its own error */ + if (resolved != NULL && cap > 0) + snprintf(resolved, cap, "%s", path); + if (tr == NULL || !tr->on) + return 1; + if (realpath(path, real) != NULL) { + if (under_root(tr, real)) { + if (resolved != NULL && cap > 0) + snprintf(resolved, cap, "%s", real); + return 1; + } + goto refused; + } + /* + * realpath() failed: the path does not exist yet (a write creating a + * file), or it is a dangling symlink. The second case is why the link + * chain is resolved here with the same function write_atomic() uses: + * a dangling link inside the root that points outside would otherwise + * pass the directory check and then be followed out of the root by the + * write. Resolving first means the check and the write agree on the + * file - which is the only way a check is worth anything. + */ + if (resolve_target(path, target, sizeof(target)) != 0) + goto refused; + snprintf(full, sizeof(full), "%s", target); + n = strlen(full); + while (n > 1 && full[n - 1] == '/') + full[--n] = '\0'; + slash = strrchr(full, '/'); + if (slash == NULL) { + snprintf(dir, sizeof(dir), "."); + base = full; + } else { + *slash = '\0'; + snprintf(dir, sizeof(dir), "%s", full[0] != '\0' ? full : "/"); + base = slash + 1; + } + /* "." or ".." as the name: nothing to create, nothing to allow */ + if (base[0] == '\0' || strcmp(base, ".") == 0 || strcmp(base, "..") == 0) + goto refused; + if (realpath(dir, dirreal) == NULL) { + /* no such directory: the tool would fail on it anyway */ + return 1; + } + n = strlen(dirreal); + /* + * Built by hand rather than with snprintf: the lengths are checked right + * here, and a "%s%s%s" into a fixed buffer makes the compiler warn about + * a truncation that this check already rules out. + */ + base_len = strlen(base); + if (n + 1 + base_len + 1 > sizeof(real)) + goto refused; + memcpy(real, dirreal, n); + real[n] = '/'; + memcpy(real + n + 1, base, base_len + 1); + if (!under_root(tr, real)) + goto refused; + if (resolved != NULL && cap > 0) + snprintf(resolved, cap, "%s", real); + return 1; +refused: + if (err != NULL) + sp_buf_printf(err, "error: %s is outside the tool root %s", path, + tr->root); + return 0; +} /* * Follow a chain of symlinks to the file that will actually be replaced. @@ -589,12 +783,11 @@ tool_read(const char *args, struct sp_buf *out, void *ctx) { struct sp_buf keep; const char *path; - char line[2048]; + char line[2048], real[TOOL_ROOT_MAX]; FILE *f; int offset, limit, no = 0, printed = 0; size_t total = 0; - (void)ctx; if (sp_buf_init(&keep) != 0) return -1; path = arg_text(args, "path", &keep); @@ -602,6 +795,11 @@ tool_read(const char *args, struct sp_buf *out, void *ctx) sp_buf_free(&keep); return sp_buf_puts(out, "error: 'path' is required"); } + if (!path_checked(ctx, path, real, sizeof(real), out)) { + sp_buf_free(&keep); + return 0; + } + path = real; offset = arg_int(args, "offset", 1); limit = arg_int(args, "limit", 200); if (offset < 1) @@ -656,9 +854,9 @@ tool_write(const char *args, struct sp_buf *out, void *ctx) { struct sp_buf keep, content; const char *path, *text; + char real[TOOL_ROOT_MAX]; size_t n; - (void)ctx; if (sp_buf_init(&keep) != 0 || sp_buf_init(&content) != 0) return -1; path = arg_text(args, "path", &keep); @@ -668,6 +866,12 @@ tool_write(const char *args, struct sp_buf *out, void *ctx) sp_buf_free(&content); return sp_buf_puts(out, "error: 'path' and 'content' are required"); } + if (!path_checked(ctx, path, real, sizeof(real), out)) { + sp_buf_free(&keep); + sp_buf_free(&content); + return 0; + } + path = real; n = strlen(text); if (n > TOOL_MAX_FILE) { sp_buf_printf(out, "error: refusing to write %zu bytes (limit %d)", @@ -781,10 +985,10 @@ tool_edit(const char *args, struct sp_buf *out, void *ctx) struct sp_buf keep, bufs[2]; const char *path, *old, *new; char *text, *hit, *result; + char real[TOOL_ROOT_MAX]; size_t len, oldlen, newlen, prefix; int count; - (void)ctx; if (sp_buf_init(&keep) != 0 || sp_buf_init(&bufs[0]) != 0 || sp_buf_init(&bufs[1]) != 0) return -1; @@ -797,6 +1001,13 @@ tool_edit(const char *args, struct sp_buf *out, void *ctx) sp_buf_free(&bufs[1]); return sp_buf_puts(out, "error: 'path', 'old' and 'new' are required"); } + if (!path_checked(ctx, path, real, sizeof(real), out)) { + sp_buf_free(&keep); + sp_buf_free(&bufs[0]); + sp_buf_free(&bufs[1]); + return 0; + } + path = real; oldlen = strlen(old); newlen = strlen(new); if (oldlen == 0) { @@ -875,11 +1086,11 @@ skip_name(const char *name) static void search_dir(const char *dir, const char *pattern, struct sp_buf *out, int *hits, - int depth) + int depth, const struct tool_root *tr) { DIR *d; struct dirent *e; - char path[1024], line[2048]; + char path[1024], real[TOOL_ROOT_MAX], line[2048]; struct stat st; if (depth > 12 || *hits >= TOOL_MAX_HITS) @@ -893,21 +1104,30 @@ search_dir(const char *dir, const char *pattern, struct sp_buf *out, int *hits, if (skip_name(e->d_name)) continue; snprintf(path, sizeof(path), "%s/%s", dir, e->d_name); - if (stat(path, &st) != 0) + /* + * Each entry is resolved before it is looked at, exactly like an + * argument: search recurses, and a directory symlink inside the root + * that points outside would otherwise be walked (stat() follows it) + * and its files read - a fence that only guards the argument is a + * fence with a door in it. + */ + if (!path_checked(tr, path, real, sizeof(real), NULL)) + continue; + if (stat(real, &st) != 0) continue; if (S_ISDIR(st.st_mode)) { - search_dir(path, pattern, out, hits, depth + 1); + search_dir(real, pattern, out, hits, depth + 1, tr); continue; } if (!S_ISREG(st.st_mode) || st.st_size > TOOL_MAX_FILE) continue; - f = fopen(path, "r"); + f = fopen(real, "r"); if (f == NULL) continue; while (fgets(line, sizeof(line), f) != NULL) { if (strstr(line, pattern) == NULL) continue; - sp_buf_printf(out, "%s: %s", path, line); + sp_buf_printf(out, "%s: %s", real, line); if (out->len > 0 && out->p[out->len - 1] != '\n') sp_buf_puts(out, "\n"); (*hits)++; @@ -926,9 +1146,9 @@ tool_search(const char *args, struct sp_buf *out, void *ctx) { struct sp_buf keep, pbuf; const char *pattern, *root; + char real[TOOL_ROOT_MAX]; int hits = 0; - (void)ctx; if (sp_buf_init(&keep) != 0 || sp_buf_init(&pbuf) != 0) return -1; pattern = arg_text(args, "pattern", &keep); @@ -938,7 +1158,14 @@ tool_search(const char *args, struct sp_buf *out, void *ctx) sp_buf_free(&pbuf); return sp_buf_puts(out, "error: 'pattern' is required"); } - search_dir(root != NULL ? root : ".", pattern, out, &hits, 0); + if (root == NULL) + root = "."; + if (!path_checked(ctx, root, real, sizeof(real), out)) { + sp_buf_free(&keep); + sp_buf_free(&pbuf); + return 0; + } + search_dir(real, pattern, out, &hits, 0, ctx); if (hits == 0) sp_buf_puts(out, "(no match)"); sp_buf_free(&keep); @@ -951,16 +1178,21 @@ tool_list(const char *args, struct sp_buf *out, void *ctx) { struct sp_buf keep; const char *path; + char real[TOOL_ROOT_MAX]; DIR *d; struct dirent *e; int n = 0; - (void)ctx; if (sp_buf_init(&keep) != 0) return -1; path = arg_text(args, "path", &keep); if (path == NULL) path = "."; + if (!path_checked(ctx, path, real, sizeof(real), out)) { + sp_buf_free(&keep); + return 0; + } + path = real; d = opendir(path); if (d == NULL) { sp_buf_printf(out, "error: %s: %s", path, strerror(errno)); @@ -968,7 +1200,7 @@ tool_list(const char *args, struct sp_buf *out, void *ctx) return 0; } while ((e = readdir(d)) != NULL && n < 300) { - char full[1024]; + char full[TOOL_ROOT_MAX + 300]; /* root path + '/' + a name */ struct stat st; if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) @@ -1228,10 +1460,44 @@ tool_webfetch(const char *args, struct sp_buf *out, void *ctx) } -int -sp_builtin_register(struct sp_registry *r) +/* + * Register one file tool with its own copy of the root. + * + * One struct per tool, because sp_registry_free() calls dispose once per tool: + * a shared pointer would be freed as often as it was registered. Every + * allocation happens before the tool is added, so a failure here leaves the + * registry as it was. + */ +static int +add_file_tool(struct sp_registry *r, const char *root, const char *name, + const char *desc, const char *params, enum sp_auth auth, sp_tool_run fn) { struct sp_tool t; + struct tool_root *tr; + + tr = tool_root_new(root); + if (tr == NULL) + return -1; + memset(&t, 0, sizeof(t)); + t.name = name; + t.description = desc; + t.params = params; + t.auth = auth; + t.run = fn; + t.ctx = tr; + t.dispose = tool_root_free; + if (sp_registry_add(r, &t) != 0) { + tool_root_free(&t); + return -1; + } + return 0; +} + +int +sp_builtin_register(struct sp_registry *r, const char *root) +{ + struct sp_tool t; + int rc = 0; memset(&t, 0, sizeof(t)); t.name = "echo"; @@ -1281,69 +1547,57 @@ sp_builtin_register(struct sp_registry *r) "\"required\":[\"command\"]}"; t.auth = SP_AUTH_DESTRUCTIVE; t.run = tool_run; - if (sp_registry_add(r, &t) != 0) + /* the shell gets the root as its working directory, not as a fence */ + t.ctx = tool_root_new(root); + t.dispose = tool_root_free; + if (t.ctx == NULL || (rc = sp_registry_add(r, &t)) != 0) { + tool_root_free(&t); return -1; + } - memset(&t, 0, sizeof(t)); - t.name = "read"; - t.description = "Read a text file. Returns numbered lines and says " - "where it stopped."; - t.params = "{\"type\":\"object\",\"properties\":{" + if (add_file_tool(r, root, "read", + "Read a text file. Returns numbered lines and says where it stopped.", + "{\"type\":\"object\",\"properties\":{" "\"path\":{\"type\":\"string\",\"description\":\"file to read\"}," "\"offset\":{\"type\":\"integer\",\"description\":\"first line, 1-based\"}," "\"limit\":{\"type\":\"integer\",\"description\":\"max lines\"}}," - "\"required\":[\"path\"]}"; - t.auth = SP_AUTH_READ; - t.run = tool_read; - if (sp_registry_add(r, &t) != 0) + "\"required\":[\"path\"]}", + SP_AUTH_READ, tool_read) != 0) return -1; - memset(&t, 0, sizeof(t)); - t.name = "write"; - t.description = "Write a file, replacing it if it exists."; - t.params = "{\"type\":\"object\",\"properties\":{" + if (add_file_tool(r, root, "write", + "Write a file, replacing it if it exists.", + "{\"type\":\"object\",\"properties\":{" "\"path\":{\"type\":\"string\"}," "\"content\":{\"type\":\"string\"}}," - "\"required\":[\"path\",\"content\"]}"; - t.auth = SP_AUTH_MUTATE; - t.run = tool_write; - if (sp_registry_add(r, &t) != 0) + "\"required\":[\"path\",\"content\"]}", + SP_AUTH_MUTATE, tool_write) != 0) return -1; - memset(&t, 0, sizeof(t)); - t.name = "edit"; - t.description = "Replace one occurrence of 'old' with 'new'. Refuses " - "when 'old' is not unique."; - t.params = "{\"type\":\"object\",\"properties\":{" + if (add_file_tool(r, root, "edit", + "Replace one occurrence of 'old' with 'new'. Refuses when 'old' is " + "not unique.", + "{\"type\":\"object\",\"properties\":{" "\"path\":{\"type\":\"string\"}," "\"old\":{\"type\":\"string\",\"description\":\"exact text to replace\"}," "\"new\":{\"type\":\"string\",\"description\":\"replacement\"}}," - "\"required\":[\"path\",\"old\",\"new\"]}"; - t.auth = SP_AUTH_MUTATE; - t.run = tool_edit; - if (sp_registry_add(r, &t) != 0) + "\"required\":[\"path\",\"old\",\"new\"]}", + SP_AUTH_MUTATE, tool_edit) != 0) return -1; - memset(&t, 0, sizeof(t)); - t.name = "search"; - t.description = "Search files under a directory for a literal string."; - t.params = "{\"type\":\"object\",\"properties\":{" + if (add_file_tool(r, root, "search", + "Search files under a directory for a literal string.", + "{\"type\":\"object\",\"properties\":{" "\"pattern\":{\"type\":\"string\"}," "\"path\":{\"type\":\"string\",\"description\":\"directory, default .\"}}," - "\"required\":[\"pattern\"]}"; - t.auth = SP_AUTH_READ; - t.run = tool_search; - if (sp_registry_add(r, &t) != 0) + "\"required\":[\"pattern\"]}", + SP_AUTH_READ, tool_search) != 0) return -1; - memset(&t, 0, sizeof(t)); - t.name = "list"; - t.description = "List a directory."; - t.params = "{\"type\":\"object\",\"properties\":{" - "\"path\":{\"type\":\"string\",\"description\":\"directory, default .\"}}}"; - t.auth = SP_AUTH_READ; - t.run = tool_list; - if (sp_registry_add(r, &t) != 0) + if (add_file_tool(r, root, "list", "List a directory.", + "{\"type\":\"object\",\"properties\":{" + "\"path\":{\"type\":\"string\",\"description\":\"directory, default .\"}}}", + SP_AUTH_READ, tool_list) != 0) return -1; return 0; diff --git a/src/backend/config.c b/src/backend/config.c index 5e95ed6..24f09e3 100644 --- a/src/backend/config.c +++ b/src/backend/config.c @@ -741,6 +741,8 @@ load_stream(struct sp_config *c, FILE *f, const char *path, set_str(c->system_prompt, sizeof(c->system_prompt), val); else if (!strcmp(key, "session_dir")) set_path(c->session_dir, sizeof(c->session_dir), val); + else if (!strcmp(key, "tools_root")) + set_path(c->tools_root, sizeof(c->tools_root), val); else if (!strcmp(key, "state_dir")) set_path(c->state_dir, sizeof(c->state_dir), val); else if (!strcmp(key, "cli_cmd")) @@ -986,6 +988,7 @@ sp_config_write_example(const char *path, struct sp_buf *err) " steps = 150 # tool rounds per turn\n" " #max_bytes = 0 # conversation budget, 0 = none\n" " #session_dir = ~/.splinter\n" + " #tools_root = ~/src # file tools stay here; empty = no fence\n" "\n" " # A usage limit is waited out: splinter finds the reset and goes on.\n" " #on_limit = wait # or fail\n" diff --git a/src/backend/config.h b/src/backend/config.h index 35d5a53..f49e4b1 100644 --- a/src/backend/config.h +++ b/src/backend/config.h @@ -141,6 +141,11 @@ struct sp_config { char theme[64]; char system_prompt[1024]; char session_dir[512]; + /* + * The boundary the file tools stay inside. Empty means none, which keeps + * a setup that works today working; see sp_builtin_register(). + */ + char tools_root[1024]; char state_dir[512]; /* config, token, commands, USER.txt; default ~/.splinter */ char cli_cmd[512]; char cli_env[SP_CONFIG_MAX_ENV][SP_CONFIG_ENV_LEN]; /* NAME=VALUE */ diff --git a/src/backend/engine.c b/src/backend/engine.c index e6c25f7..d049166 100644 --- a/src/backend/engine.c +++ b/src/backend/engine.c @@ -3804,9 +3804,20 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o, snprintf(e->cur_model, sizeof(e->cur_model), "%s", o->conf->model); - if (sp_builtin_register(&e->reg) != 0 || + if (sp_builtin_register(&e->reg, e->conf != NULL ? + e->conf->tools_root : NULL) != 0 || sp_skills_register(&e->reg, e->conf) != 0) { - sp_buf_puts(err, "cannot register the builtin tools"); + /* + * A tools_root that cannot be resolved is the one failure a + * working setup hits here, so it is named: "cannot register" + * alone sends the operator looking at the wrong thing. + */ + if (e->conf != NULL && e->conf->tools_root[0] != '\0') + sp_buf_printf(err, "cannot register the builtin tools " + "(tools_root = %s: not an existing directory)", + e->conf->tools_root); + else + sp_buf_puts(err, "cannot register the builtin tools"); goto fail; } if (open_session(e, o, err, &code, &placeholder) != 0) diff --git a/tests/test_builtin.c b/tests/test_builtin.c index 930401f..c9cf9cc 100644 --- a/tests/test_builtin.c +++ b/tests/test_builtin.c @@ -48,6 +48,18 @@ write_file(const char *path, const char *text) } } +/* + * The context a tool was registered with: the tools keep their root there, and + * a test that calls run() directly has to hand it over the way the agent does. + */ +static void * +tool_ctx(struct sp_registry *r, const char *name) +{ + const struct sp_tool *t = tool(r, name); + + return t != NULL ? t->ctx : NULL; +} + int main(void) { @@ -65,7 +77,7 @@ main(void) memset(&r, 0, sizeof(r)); if (sp_buf_init(&out) != 0) return 1; - CHECK(sp_builtin_register(&r) == 0); + CHECK(sp_builtin_register(&r, NULL) == 0); /* the five tools exist and declare their class */ CHECK(tool(&r, "read")->auth == SP_AUTH_READ); @@ -343,6 +355,153 @@ main(void) copy = out.p; CHECK(copy != NULL); + /* + * ---- tools_root: the file tools stay inside it ---- + * + * Without a root a model with mutate rights can write anything the + * process can: ~/.ssh/authorized_keys, the config that names the + * plugins. The classes say *whether* a tool may run, not *where* - so + * the root is the boundary, and it has to hold for every entry the + * model can spell: an absolute path outside, a "../.." walk, and a + * symlink inside that points outside. + */ + { + struct sp_registry r2; + struct sp_buf out2; + char root[700], outside[700], link[700]; + char req[1600]; + struct stat st; + + snprintf(root, sizeof(root), "%s/rootdir", dir); + snprintf(outside, sizeof(outside), "%s/outside.txt", dir); + snprintf(link, sizeof(link), "%s/rootdir/escape", dir); + CHECK(mkdir(root, 0700) == 0); + write_file(outside, "geheim\n"); + CHECK(symlink(outside, link) == 0); + + memset(&r2, 0, sizeof(r2)); + if (sp_buf_init(&out2) != 0) + return 1; + CHECK(sp_builtin_register(&r2, root) == 0); + + /* inside: allowed, and it works */ + sp_buf_clear(&out2); + snprintf(req, sizeof(req), + "{\"path\":\"%s/drin.txt\",\"content\":\"ok\"}", root); + CHECK(tool(&r2, "write")->run(req, &out2, tool_ctx(&r2, "write")) == 0); + CHECK(strstr(out2.p, "wrote") != NULL); + + /* absolute path outside: refused, and nothing was written */ + sp_buf_clear(&out2); + snprintf(req, sizeof(req), + "{\"path\":\"%s/pwned.txt\",\"content\":\"x\"}", outside); + CHECK(tool(&r2, "write")->run(req, &out2, tool_ctx(&r2, "write")) == 0); + CHECK(strstr(out2.p, "outside the tool root") != NULL); + CHECK(stat(outside, &st) == 0); + CHECK(st.st_size == 7); /* "geheim\n" - not overwritten */ + + /* ../.. walk: refused */ + sp_buf_clear(&out2); + snprintf(req, sizeof(req), + "{\"path\":\"%s/../../pwned2.txt\",\"content\":\"x\"}", root); + CHECK(tool(&r2, "write")->run(req, &out2, tool_ctx(&r2, "write")) == 0); + CHECK(strstr(out2.p, "outside the tool root") != NULL); + + /* a symlink inside that points outside: refused */ + sp_buf_clear(&out2); + snprintf(req, sizeof(req), "{\"path\":\"%s\"}", link); + CHECK(tool(&r2, "read")->run(req, &out2, tool_ctx(&r2, "read")) == 0); + CHECK(strstr(out2.p, "outside the tool root") != NULL); + CHECK(strstr(out2.p, "geheim") == NULL); + + /* + * A *dangling* link inside the root that points outside: realpath() + * cannot resolve it (the target does not exist yet), so a check that + * only looked at the directory would say "inside" - and the write + * then follows the link out of the root. This is the case that made + * the fence worthless, so it is tested separately. + */ + { + char dangling[700], victim[700]; + + snprintf(dangling, sizeof(dangling), "%s/rootdir/dangling", + dir); + snprintf(victim, sizeof(victim), "%s/created-by-model.txt", + dir); + CHECK(symlink(victim, dangling) == 0); + sp_buf_clear(&out2); + snprintf(req, sizeof(req), + "{\"path\":\"%s\",\"content\":\"pwned\\n\"}", + dangling); + CHECK(tool(&r2, "write")->run(req, &out2, + tool_ctx(&r2, "write")) == 0); + CHECK(strstr(out2.p, "outside the tool root") != NULL); + CHECK(access(victim, F_OK) != 0); /* not created */ + } + + /* read, search and list are fenced too */ + sp_buf_clear(&out2); + snprintf(req, sizeof(req), "{\"path\":\"%s\"}", outside); + CHECK(tool(&r2, "read")->run(req, &out2, tool_ctx(&r2, "read")) == 0); + CHECK(strstr(out2.p, "outside the tool root") != NULL); + + sp_buf_clear(&out2); + snprintf(req, sizeof(req), + "{\"pattern\":\"geheim\",\"path\":\"%s\"}", dir); + CHECK(tool(&r2, "search")->run(req, &out2, tool_ctx(&r2, "search")) == 0); + CHECK(strstr(out2.p, "outside the tool root") != NULL); + + sp_buf_clear(&out2); + snprintf(req, sizeof(req), "{\"path\":\"%s\"}", dir); + CHECK(tool(&r2, "list")->run(req, &out2, tool_ctx(&r2, "list")) == 0); + CHECK(strstr(out2.p, "outside the tool root") != NULL); + + /* + * search recurses, and stat() follows a directory symlink: a link + * inside the root that points outside would be walked and its files + * read. Guarding the argument alone is not enough, so every entry is + * resolved too. + */ + { + char outside_dir[700], link_out[700], secret[800]; + char inner[700]; + + snprintf(outside_dir, sizeof(outside_dir), "%s/secretdir", + dir); + snprintf(secret, sizeof(secret), "%s/note.txt", + outside_dir); + if (mkdir(outside_dir, 0700) == 0) { + write_file(secret, "GEHEIM-NOTE\n"); + snprintf(link_out, sizeof(link_out), + "%s/rootdir/linkout", dir); + CHECK(symlink(outside_dir, link_out) == 0); + sp_buf_clear(&out2); + snprintf(req, sizeof(req), + "{\"pattern\":\"GEHEIM\",\"path\":\"%s\"}", + root); + CHECK(tool(&r2, "search")->run(req, &out2, + tool_ctx(&r2, "search")) == 0); + CHECK(strstr(out2.p, "GEHEIM-NOTE") == NULL); + } + /* a search that stays inside still finds what is there */ + snprintf(inner, sizeof(inner), "%s/rootdir/inner.txt", + dir); + write_file(inner, "TREFFER-DRINN\n"); + sp_buf_clear(&out2); + snprintf(req, sizeof(req), + "{\"pattern\":\"TREFFER\",\"path\":\"%s\"}", root); + CHECK(tool(&r2, "search")->run(req, &out2, + tool_ctx(&r2, "search")) == 0); + CHECK(strstr(out2.p, "TREFFER-DRINN") != NULL); + } + + sp_registry_free(&r2); + sp_buf_free(&out2); + + /* the tree outside the root was never touched by a refusal */ + CHECK(access(outside, F_OK) == 0); + } + sp_registry_free(&r); sp_buf_free(&out); { diff --git a/tests/test_config.c b/tests/test_config.c index b0da5d7..d045b60 100644 --- a/tests/test_config.c +++ b/tests/test_config.c @@ -69,7 +69,8 @@ main(void) "mcp = files | cmd=npx -y server-filesystem /home\n" "delegate = c2 | zweites Konto | kind=cli | cmd=claude -p | " "env=CLAUDE_CODE_OAUTH_TOKEN=abc | env=FOO=bar baz\n" - "system_prompt = sei knapp\n"); + "system_prompt = sei knapp\n" + "tools_root = /home/konrad/src\n"); sp_config_init(&c); sp_buf_clear(&err); @@ -102,8 +103,36 @@ main(void) c.delegate[0].nenv); CHECK(getenv("FOO") != NULL && strcmp(getenv("FOO"), "bar baz") == 0); CHECK(strcmp(c.system_prompt, "sei knapp") == 0); + CHECK(strcmp(c.tools_root, "/home/konrad/src") == 0); /* untouched defaults survive */ CHECK(strcmp(c.key_env, "SPLINTER_API_KEY") == 0); + CHECK(c.tools_root[0] != '\0'); /* set above, not reset */ + + /* ---- a leading ~ is the home directory, not a directory named "~" --- */ + { + const char *home = getenv("HOME"); + + write_file(path, + "session_dir = ~/.splinter\n" + "tools_root = ~/src\n" + "skills_dir = ~/skills\n" + "state_dir = /tmp/state\n"); + sp_config_init(&c); + sp_buf_clear(&err); + CHECK(sp_config_load(&c, path, &err) == 0); + if (home != NULL && *home != '\0') { + char want[512]; + + snprintf(want, sizeof(want), "%s/.splinter", home); + CHECK(strcmp(c.session_dir, want) == 0); + snprintf(want, sizeof(want), "%s/src", home); + CHECK(strcmp(c.tools_root, want) == 0); + snprintf(want, sizeof(want), "%s/skills", home); + CHECK(strcmp(c.skills_dir[0], want) == 0); + } + /* an absolute path is left exactly as written */ + CHECK(strcmp(c.state_dir, "/tmp/state") == 0); + } /* ---- a leading ~ is the home directory, not a directory named "~" --- */ { diff --git a/tests/test_secrets.c b/tests/test_secrets.c index e402aa0..be26a12 100644 --- a/tests/test_secrets.c +++ b/tests/test_secrets.c @@ -71,7 +71,7 @@ test_run(void) time_t t0; memset(&r, 0, sizeof(r)); - CHECK(sp_builtin_register(&r) == 0); + CHECK(sp_builtin_register(&r, NULL) == 0); CHECK(sp_buf_init(&out) == 0); setenv("SPLINTER_API_KEY", "sk-geheim-1", 1); @@ -225,7 +225,7 @@ test_mcp(void) pid_t srv; memset(&r, 0, sizeof(r)); - CHECK(sp_builtin_register(&r) == 0); + CHECK(sp_builtin_register(&r, NULL) == 0); CHECK(sp_buf_init(&err) == 0); unsetenv("SPLINTER_MCP_TOKEN");