Skip to content

Commit 7f1ba2b

Browse files
committed
feat:whitelist some commands
1 parent 6e70168 commit 7f1ba2b

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

gptme/tools/shell.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -243,15 +243,27 @@ def execute_shell(
243243
"""Executes a shell command and returns the output."""
244244
shell = get_shell()
245245
assert not args
246+
whitelist_commands = ["ls", "stat", "cd", "cat", "pwd", "echo"]
247+
whitelisted = True
246248

247249
cmd = code.strip()
248250
if cmd.startswith("$ "):
249251
cmd = cmd[len("$ ") :]
250252

251-
print_preview(cmd, "bash")
252-
if not confirm("Run command?"):
253-
yield Message("system", "Command not run")
254-
return
253+
#NOTE: This does not handle control flow words like if, for, while.
254+
regex = r"(?:^|[|&;]|\|\||&&|\n)\s*([^\s|&;]+)"
255+
256+
for match in re.finditer(regex, cmd):
257+
for group in match.groups():
258+
if group and group not in whitelist_commands:
259+
whitelisted = False
260+
break
261+
262+
if not whitelisted:
263+
print_preview(cmd, "bash")
264+
if not confirm("Run command?"):
265+
yield Message("system", "Command not run")
266+
return
255267

256268
try:
257269
returncode, stdout, stderr = shell.run(cmd)
@@ -261,7 +273,7 @@ def execute_shell(
261273
stdout = _shorten_stdout(stdout.strip(), pre_tokens=2000, post_tokens=8000)
262274
stderr = _shorten_stdout(stderr.strip(), pre_tokens=2000, post_tokens=2000)
263275

264-
msg = _format_block_smart("Ran command", cmd, lang="bash") + "\n\n"
276+
msg = _format_block_smart(f"Ran {'whitelisted ' if whitelisted else ''}command", cmd, lang="bash") + "\n\n"
265277
if stdout:
266278
msg += _format_block_smart("", stdout, "stdout") + "\n\n"
267279
if stderr:

0 commit comments

Comments
 (0)