Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(safety): keep a substitution from reading the outer heredoc body

DheerajPiduru52c3967e541fdd
diff --git a/server/safety-floor.test.ts b/server/safety-floor.test.ts
index 8031841f1d..64b7becdeb 100644
--- a/server/safety-floor.test.ts
+++ b/server/safety-floor.test.ts
@@ -153,6 +153,9 @@ const BLOCKED: Case[] = [
['echo "${X:-"$(rm -rf /)"}"', "delete-root"],
[': "${DIR:=`rm -rf ~`}"', "delete-home"],
["files=( $(mkfs.ext4 /dev/sda1) )", "format-disk"],
+ // a newline inside a substitution does not start the outer heredoc's body
+ [": <<EOF ${X:-$(printf ok\n)}; ( rm -rf ~\nEOF\n); echo }", "delete-home"],
+ [": <<EOF $(printf ok\n); ( rm -rf ~\nEOF\n)", "delete-home"],
["rm -rf \\\n /", "delete-root"],
// formatting or overwriting a disk
["mkfs.ext4 /dev/sda1", "format-disk"],
@@ -628,7 +631,8 @@ const NOT_CLEAR: Array<[command: string, on: Platform | "posix" | "all", outcome
["x=$((2 << 3)); echo $x", "all", "unreadable"],
["(( x << 1 ))\nrm -rf /", "all", "unreadable"],
["echo $[1<<2]\nrm -rf /", "all", "unreadable"],
- ["echo $((1 << 2))\nrm -rf /", "all", "unreadable"],
+ // inside `$(( … ))` the heredoc stays in the substitution, so the next line is still read
+ ["echo $((1 << 2))\nrm -rf /", "all", "delete-root"],
// `env -S` expands `$NAME`, reads backslashes and drops `#` comments by
// rules of its own, and a value the shell computed is not known
["env -S 'rm -rf ${TARGET}'", "all", "unreadable"],
diff --git a/server/safety-floor.ts b/server/safety-floor.ts
index 0a7e5816e5..001da68be6 100644
--- a/server/safety-floor.ts
+++ b/server/safety-floor.ts
@@ -105,11 +105,15 @@ function lex(source: string, windows: boolean): Reading {
};
const nested = (shut: string) => {
+ // Bash reads a pending heredoc body after the line, not at a newline inside a substitution on it.
+ const outer = heredocs.splice(0);
if (++nesting > MAX_NESTING) {
at = source.length;
synced = false;
} else if (!script(shut)) synced = false;
nesting--;
+ if (heredocs.length) synced = false;
+ heredocs.splice(0, heredocs.length, ...outer);
};
/** Reads a POSIX `$(…)` or backtick substitution at `at` as commands, and leaves `at` on its last character. */
const substitution = (): boolean => {