Files
splinter/src/telegram.c
T
lotherkandClaude Opus 5.5 6fe30f4787 security: the authorization model holds where the model writes the input
A review found the tool classes - the core of the harness - bypassable in
several places where model output was pasted into a shell or trusted as an id.
Each fix below has a test that reproduces the original failure.

No shell for model data
- webfetch put the URL between '...' and ran it through popen: a quote in the
  URL ran any command, from a tool that needed no consent. curl is now exec'd
  with an argv, http(s) only, HTML stripped in C, stderr off the curses screen.
- webfetch is mutate: with read free, "read a key, fetch evil/?k=..." left the
  machine without anybody being asked. websearch stays read (fixed host).
- kids: the parent-approval command got the model's arguments inside '...'
  via system(); they are now "$1". The domain check reads the URL with the
  same parser as the tool (duplicate keys) and refuses user@host URLs.
- delegate: the two copies of the child argv are one (exec_delegate). The ssh
  path exec'd splinter with "ssh" as argv[0]; it now runs ssh and quotes every
  word for the remote shell. A single delegate to a host now really runs there.

Approvals (ack)
- The id was the pid: a late yes stayed on disk and approved the next request
  unseen. Ids are random, requests 0600 with O_EXCL, deleted when answered or
  expired; an answer is refused after expiry; the first answer wins (link(2)).
- An ack dir owned by someone else or writable by others is refused.
- --ack accepted every word but "no" as yes ("nein" approved). Now strict.
- The terminal thread blocked in fgets after a phone answer; it is stoppable.

Secrets
- API key and Telegram token were in curl's argv, readable via ps. src/curl.c
  passes URL and auth headers as a -K config on stdin (transport, telegram,
  tg-ask.sh; its dead eval fallback is gone).
- 'run' and task_start no longer inherit splinter's keys ("run env"). 'run' got
  its own process group, stdin /dev/null and SPLINTER_RUN_TIMEOUT (300 s).

MCP server
- Beyond 127.x it refuses to start without SPLINTER_MCP_TOKEN; connections
  must begin with "AUTH <token>". SIGPIPE ignored, idle connections closed.

Crashes
- task_kill sent kill(-0) - SIGTERM to splinter's own process group - because
  popen gave no pid. Tasks now have a pid and a process group; integer ids work.
- ui: a 3- or 4-byte UTF-8 character overflowed char[2] on every redraw
  (now sp_ui_ascii_char, tested); the scroll offset was taken from one buffer
  and applied to another, reading past its end.

Repo
- The test binaries are no longer tracked (.gitignore already said so).

make check: 23 test binaries, green, also under ASan/UBSan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 20:19:01 +00:00

466 lines
11 KiB
C

/*
* splinter -- the gateway mode.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* A daemon that answers on Telegram: long-polls getUpdates, runs one turn per
* message, replies. No curses, no terminal - the same agent, driven by a socket.
*
* Rules that are not negotiable here:
*
* - the token is read from a file (0600) or the environment, never from an
* argument: an argument ends up in ps and in shell history;
* - only the configured users are answered. Everyone else is ignored, and the
* message is logged without its text;
* - a failed request is reported and the loop continues. A gateway that dies
* on one bad message is a gateway that is down until someone notices.
*
* The offset is kept in memory only: a restart re-delivers the last update,
* which costs one duplicated answer and never a lost message.
*/
#include <errno.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "ack.h"
#include "curl.h"
#include "splinter.h"
#include "mcp.h"
#include "log.h"
#include "cmdscript.h"
#include "splinter_plugin.h"
/*
* Where the API lives. Overridable, because a gateway you cannot test without
* Telegram is a gateway you only test in production.
*/
static const char *
api_base(void)
{
const char *env = getenv("SPLINTER_TELEGRAM_API");
return env != NULL && *env != '\0' ? env : "https://api.telegram.org";
}
#define TG_MAX_CHUNK 3500
#define TG_POLL_S 25
static volatile int tg_stop;
static int tg_curl(const char *url, const char *post_body, struct sp_buf *out,
struct sp_buf *err);
/* Telegram shows "typing" for about five seconds; a turn takes longer. */
struct typing {
char token[256];
long chat_id;
volatile int *stop;
};
static void *
typing_thread(void *arg)
{
struct typing *t = arg;
struct sp_buf url, reply, err;
int i;
if (sp_buf_init(&url) != 0 || sp_buf_init(&reply) != 0 ||
sp_buf_init(&err) != 0)
return NULL;
sp_buf_printf(&url, "%s/bot%s/sendChatAction", api_base(), t->token);
{
struct sp_buf body;
if (sp_buf_init(&body) != 0)
return NULL;
sp_buf_printf(&body, "{\"chat_id\":%ld,\"action\":\"typing\"}",
t->chat_id);
for (i = 0; i < 300 && *t->stop == 0; i++) {
sp_buf_clear(&reply);
(void)tg_curl(url.p, body.p, &reply, &err);
sp_buf_clear(&err);
sleep(4);
}
sp_buf_free(&body);
}
sp_buf_free(&url);
sp_buf_free(&reply);
sp_buf_free(&err);
return NULL;
}
static void
on_signal(int sig)
{
(void)sig;
tg_stop = 1;
}
/*
* Run curl with the URL built here and return its stdout.
*
* The token is part of the URL, and an argument is readable by every user of
* the machine. So the URL goes to curl on stdin (sp_curl_start), and argv holds
* nothing that would let anybody else drive the bot.
*/
static int
tg_curl(const char *url, const char *post_body, struct sp_buf *out,
struct sp_buf *err)
{
int fds[2];
pid_t child;
const char *args[12];
int n = 0;
args[n++] = "-sS";
args[n++] = "-m";
args[n++] = "60";
if (post_body != NULL) {
args[n++] = "-X";
args[n++] = "POST";
args[n++] = "-H";
args[n++] = "Content-Type: application/json";
args[n++] = "--data-binary";
args[n++] = post_body;
}
args[n] = NULL;
fds[0] = sp_curl_start(args, url, NULL, 0, &child, err);
if (fds[0] < 0)
return -1;
{
struct pollfd pfd;
char chunk[4096];
for (;;) {
ssize_t got;
pfd.fd = fds[0];
pfd.events = POLLIN;
if (poll(&pfd, 1, 90000) <= 0) {
(void)kill(child, SIGKILL);
break;
}
got = read(fds[0], chunk, sizeof(chunk));
if (got <= 0)
break;
if (sp_buf_add(out, chunk, (size_t)got) != 0)
break;
}
}
close(fds[0]);
{
int st = 0;
(void)waitpid(child, &st, 0);
if (!WIFEXITED(st) || WEXITSTATUS(st) != 0) {
sp_buf_printf(err, "telegram: curl failed (%d)",
WIFEXITED(st) ? WEXITSTATUS(st) : -1);
return -1;
}
}
return 0;
}
static int
send_message(const char *token, long chat_id, const char *text,
struct sp_buf *err)
{
struct sp_buf url, body, reply;
size_t off = 0, len = strlen(text);
int rc = 0;
if (sp_buf_init(&url) != 0 || sp_buf_init(&body) != 0 ||
sp_buf_init(&reply) != 0)
return -1;
sp_buf_printf(&url, "%s/bot%s/sendMessage", api_base(), token);
do {
size_t take = len - off;
if (take > TG_MAX_CHUNK)
take = TG_MAX_CHUNK;
sp_buf_clear(&body);
sp_buf_printf(&body, "{\"chat_id\":%ld,\"text\":\"", chat_id);
{
char *piece = malloc(take + 1);
if (piece == NULL) {
rc = -1;
break;
}
memcpy(piece, text + off, take);
piece[take] = '\0';
(void)sp_json_escape(&body, piece);
free(piece);
}
sp_buf_puts(&body, "\"}");
sp_buf_clear(&reply);
if (tg_curl(url.p, body.p, &reply, err) != 0) {
rc = -1;
break;
}
if (strstr(reply.p != NULL ? reply.p : "", "\"ok\":true") == NULL) {
sp_buf_printf(err, "telegram: sendMessage refused: %.200s",
reply.p != NULL ? reply.p : "");
rc = -1;
break;
}
off += take;
} while (off < len);
sp_buf_free(&url);
sp_buf_free(&body);
sp_buf_free(&reply);
return rc;
}
/* Is this update for a user we answer? */
static int
allowed(const char *allow, long id)
{
char copy[256], *p, *save = NULL;
if (allow == NULL || *allow == '\0')
return 0; /* empty means nobody */
snprintf(copy, sizeof(copy), "%s", allow);
for (p = strtok_r(copy, ", ", &save); p != NULL;
p = strtok_r(NULL, ", ", &save))
if (strtol(p, NULL, 10) == id)
return 1;
return 0;
}
int
sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
const char *allow, struct sp_buf *err)
{
long offset = 0;
struct sp_buf url, reply, answer, aerr;
if (sp_buf_init(&url) != 0 || sp_buf_init(&reply) != 0 ||
sp_buf_init(&answer) != 0 || sp_buf_init(&aerr) != 0)
return -1;
(void)signal(SIGINT, on_signal);
(void)signal(SIGTERM, on_signal);
fprintf(stderr, "splinter: gateway listening (allow: %s)\n",
allow != NULL && *allow != '\0' ? allow : "nobody");
while (!tg_stop) {
mcp_json *v;
const mcp_json *result, *update;
int ok;
sp_buf_clear(&url);
sp_buf_printf(&url, "%s/bot%s/getUpdates?timeout=%d&offset=%ld",
api_base(), token, TG_POLL_S, offset);
sp_buf_clear(&reply);
if (tg_curl(url.p, NULL, &reply, err) != 0) {
fprintf(stderr, "splinter: %s\n",
err->p != NULL ? err->p : "poll failed");
sp_buf_clear(err);
sleep(3);
continue;
}
v = mcp_parse(reply.p);
if (v == NULL)
continue;
ok = mcp_arg_bool(v, "ok", 0);
result = mcp_arg(v, "result");
if (!ok || result == NULL) {
mcp_json_free(v);
sleep(3);
continue;
}
/* updates come as an array; libmcp hands them out by index */
{
size_t i;
for (i = 0; (update = mcp_array_at(result, i)) != NULL;
i++) {
const mcp_json *msg;
const char *text, *prompt_used = NULL;
char prompt[4096];
pthread_t tty;
volatile int tstop = 0;
struct typing ty;
int typing_on = 0;
long chat_id, from;
int update_id;
update_id = mcp_arg_int(update, "update_id", 0);
offset = (long)update_id + 1;
msg = mcp_arg(update, "message");
if (msg == NULL)
continue;
text = mcp_arg_string(msg, "text");
chat_id = mcp_arg_int(mcp_arg(msg, "chat"),
"id", 0);
from = mcp_arg_int(mcp_arg(msg, "from"),
"id", 0);
if (text == NULL || *text == '\0' || chat_id == 0)
continue;
if (!allowed(allow, from)) {
fprintf(stderr, "splinter: ignoring "
"message from %ld\n", from);
continue;
}
sp_buf_clear(&answer);
sp_buf_clear(&aerr);
/*
* A slash command is the harness talking, not the
* model: /goal and /recap come from plugins and
* answer without a request.
*/
/*
* An answer to a pending approval. The gateway is the one
* reader of this chat, so it resolves here instead of letting a
* second poller fight it for updates.
*/
if (strncmp(text, "ok ", 3) == 0 || strncmp(text, "no ", 3) == 0 ||
strncmp(text, "ja ", 3) == 0 || strncmp(text, "nein ", 5) == 0) {
const char *num = strchr(text, ' ');
int id = num != NULL ? atoi(num + 1) : 0;
if (id > 0) {
int yes = text[0] == 'o' || text[0] == 'j';
if (sp_ack_answer(id, yes, "telegram") == 0)
(void)send_message(token, chat_id,
yes ? "Zustimmung erteilt." :
"Abgelehnt.", NULL);
else
(void)send_message(token, chat_id,
"Diese Anfrage gibt es nicht (mehr).", NULL);
continue;
}
}
if (text[0] == '/' && text[1] != '\0') {
char name[32], *rest;
size_t n = strcspn(text + 1, " ");
int crc;
snprintf(name, sizeof(name), "%.*s",
(int)n, text + 1);
rest = (char *)text + 1 + n;
while (*rest == ' ')
rest++;
crc = host != NULL ?
sp_host_command(host, name, rest,
&answer) : -1;
if (crc == 0) {
(void)send_message(token, chat_id,
answer.p != NULL ? answer.p :
"(leer)", err);
sp_buf_clear(err);
continue;
}
/*
* Not a plugin command: a program in
* commands/ gets the rest of the line and its
* output becomes the model's context.
*/
{
char cdir[700];
struct sp_buf cerr;
sp_buf_init(&cerr);
if (sp_cmdscript_dir(ag->sess != NULL ?
ag->sess->dir : NULL, cdir,
sizeof(cdir)) == 0 &&
sp_cmdscript_exists(cdir, name) &&
sp_slash_script(cdir, name, rest,
&answer, &cerr) == 0 &&
answer.p != NULL) {
snprintf(prompt, sizeof(prompt),
"%s", answer.p);
prompt_used = prompt;
}
sp_buf_free(&cerr);
}
}
/* "typing" while the model thinks, not while a
* plugin answers a slash command */
snprintf(ty.token, sizeof(ty.token), "%s", token);
ty.chat_id = chat_id;
ty.stop = &tstop;
if (pthread_create(&tty, NULL, typing_thread,
&ty) == 0)
typing_on = 1;
if (sp_agent_run(ag, prompt_used != NULL ?
prompt_used : text, &answer, &aerr) != 0) {
(void)send_message(token, chat_id,
aerr.p != NULL ? aerr.p :
"turn failed", err);
if (typing_on) {
tstop = 1;
(void)pthread_join(tty, NULL);
}
sp_buf_clear(err);
continue;
}
if (typing_on) {
tstop = 1;
(void)pthread_join(tty, NULL);
}
(void)send_message(token, chat_id,
answer.p != NULL ? answer.p : "(leer)", err);
sp_buf_clear(err);
/* the agent already recorded both sides */
}
}
mcp_json_free(v);
}
sp_buf_free(&url);
sp_buf_free(&reply);
sp_buf_free(&answer);
sp_buf_free(&aerr);
fprintf(stderr, "splinter: gateway stopped\n");
return 0;
}
/*
* The token: file first (0600), then environment. A token on disk can be locked
* down; a token in an argument cannot.
*/
int
sp_telegram_token(char *buf, size_t len, const char *path)
{
FILE *f;
char line[256];
f = fopen(path, "r");
if (f != NULL) {
size_t n;
if (fgets(line, sizeof(line), f) == NULL) {
fclose(f);
return -1;
}
fclose(f);
n = strcspn(line, "\r\n");
line[n] = '\0';
if (line[0] == '\0')
return -1;
snprintf(buf, len, "%s", line);
return 0;
}
{
const char *env = getenv("SPLINTER_TELEGRAM_TOKEN");
if (env == NULL || *env == '\0')
return -1;
snprintf(buf, len, "%s", env);
}
return 0;
}