Run subprocesses as unprivileged user

This commit is contained in:
Mattéo Delabre 2021-01-27 20:16:31 +01:00
parent a1baf3ad3f
commit f2abe9dcf6
Signed by: matteo
GPG Key ID: AE3FBD02DC583ABB
3 changed files with 14 additions and 7 deletions

View File

@ -1,8 +1,7 @@
FROM alpine
RUN apk add --no-cache bash python3
RUN adduser -D user
USER user
WORKDIR /home/user
ADD autogolf /home/user/autogolf
ADD run.py /home/user
RUN adduser -D -H -u 1337 user
WORKDIR /root
ADD autogolf /root/autogolf
ADD run.py /root
CMD ["python3", "run.py"]

View File

@ -5,5 +5,5 @@ How to run:
```
docker image build --quiet --tag runall-image .
mkdir output
docker container run --tty --rm --mount type=bind,src="$(realpath output)",dst=/home/user/output --memory=128m runall-image
docker container run --tty --rm --mount type=bind,src="$(realpath output)",dst=/root/output --memory=128m runall-image
```

View File

@ -2,6 +2,7 @@ from enum import Enum, auto
from functools import partial
from itertools import product
from multiprocessing import Pool
import os
from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired
from time import time
from typing import List
@ -17,6 +18,12 @@ class Status(Enum):
Timeout = auto() # ran for more time than allowed by the timeout value
def demote():
"""Drop root privileges."""
os.setgid(1337)
os.setuid(1337)
def check_pair(script, instr, outstr, timeout) -> Status:
"""
Check that a Bash script outputs a given string when given a input string.
@ -29,13 +36,14 @@ def check_pair(script, instr, outstr, timeout) -> Status:
"""
process = Popen(
[
"/bin/bash", "--restricted", "-c", "--",
"/bin/bash", "-c", "--",
"trap 'kill -9 $(jobs -p) && wait' SIGINT SIGTERM EXIT;\n"
+ script,
],
stdin=PIPE,
stdout=PIPE,
stderr=DEVNULL,
preexec_fn=demote,
)
try: