165 lines
3.6 KiB
Python
165 lines
3.6 KiB
Python
"""Explicitly authorised, non-interactive command execution."""
|
|
|
|
import os
|
|
import shutil
|
|
import signal
|
|
import subprocess
|
|
import tempfile
|
|
|
|
|
|
class ExecutionError(RuntimeError):
|
|
"""Command execution failed or was prohibited."""
|
|
|
|
|
|
def normalise_command(command):
|
|
|
|
if (
|
|
not isinstance(command, (tuple, list))
|
|
or not command
|
|
):
|
|
|
|
raise ExecutionError(
|
|
"Invalid command"
|
|
)
|
|
|
|
if any(
|
|
not isinstance(argument, str)
|
|
or "\x00" in argument
|
|
for argument in command
|
|
):
|
|
|
|
raise ExecutionError(
|
|
"Invalid command argument"
|
|
)
|
|
|
|
if not command[0]:
|
|
|
|
raise ExecutionError(
|
|
"Missing executable"
|
|
)
|
|
|
|
return tuple(command)
|
|
|
|
|
|
class CommandRunner:
|
|
|
|
def __init__(
|
|
self,
|
|
allowed_commands,
|
|
timeout=300,
|
|
):
|
|
|
|
if (
|
|
type(timeout) is not int
|
|
or not 1 <= timeout <= 3600
|
|
):
|
|
|
|
raise ExecutionError(
|
|
"Invalid command timeout"
|
|
)
|
|
|
|
self.allowed = frozenset(
|
|
normalise_command(command)
|
|
for command in allowed_commands
|
|
)
|
|
|
|
if not self.allowed:
|
|
|
|
raise ExecutionError(
|
|
"Command allowlist is empty"
|
|
)
|
|
|
|
self.timeout = timeout
|
|
|
|
def __call__(self, command, output):
|
|
|
|
command = normalise_command(command)
|
|
|
|
if command not in self.allowed:
|
|
|
|
raise ExecutionError(
|
|
"Command is not authorised"
|
|
)
|
|
|
|
if not callable(
|
|
getattr(output, "write", None)
|
|
):
|
|
|
|
raise ExecutionError(
|
|
"Invalid output destination"
|
|
)
|
|
|
|
# Stage output privately until the subprocess
|
|
# has completed successfully. No partial output
|
|
# is published on command failure.
|
|
|
|
with tempfile.TemporaryFile(
|
|
mode="w+b"
|
|
) as staged:
|
|
|
|
try:
|
|
|
|
process = subprocess.Popen(
|
|
command,
|
|
stdin=subprocess.DEVNULL,
|
|
stdout=staged,
|
|
stderr=subprocess.DEVNULL,
|
|
shell=False,
|
|
# Resolve bare executables via the OS default path and
|
|
# exclude ambient credentials and runtime overrides.
|
|
env={"PATH": os.defpath, "LC_ALL": "C"},
|
|
start_new_session=True,
|
|
)
|
|
|
|
except OSError:
|
|
|
|
raise ExecutionError(
|
|
"Unable to start authorised command"
|
|
) from None
|
|
|
|
try:
|
|
|
|
status = process.wait(
|
|
timeout=self.timeout
|
|
)
|
|
|
|
except BaseException as error:
|
|
|
|
try:
|
|
|
|
os.killpg(
|
|
process.pid,
|
|
signal.SIGKILL,
|
|
)
|
|
|
|
except ProcessLookupError:
|
|
|
|
pass
|
|
|
|
process.wait()
|
|
|
|
if isinstance(
|
|
error,
|
|
subprocess.TimeoutExpired,
|
|
):
|
|
|
|
raise ExecutionError(
|
|
"Command execution timed out"
|
|
) from None
|
|
|
|
raise
|
|
|
|
if status != 0:
|
|
|
|
raise ExecutionError(
|
|
f"Command exited with status {status}"
|
|
)
|
|
|
|
staged.seek(0)
|
|
|
|
shutil.copyfileobj(
|
|
staged,
|
|
output,
|
|
length=1024 * 1024,
|
|
)
|