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 FROM alpine
RUN apk add --no-cache bash python3 RUN apk add --no-cache bash python3
RUN adduser -D user RUN adduser -D -H -u 1337 user
USER user WORKDIR /root
WORKDIR /home/user ADD autogolf /root/autogolf
ADD autogolf /home/user/autogolf ADD run.py /root
ADD run.py /home/user
CMD ["python3", "run.py"] CMD ["python3", "run.py"]

View File

@ -5,5 +5,5 @@ How to run:
``` ```
docker image build --quiet --tag runall-image . docker image build --quiet --tag runall-image .
mkdir output 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 functools import partial
from itertools import product from itertools import product
from multiprocessing import Pool from multiprocessing import Pool
import os
from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired
from time import time from time import time
from typing import List from typing import List
@ -17,6 +18,12 @@ class Status(Enum):
Timeout = auto() # ran for more time than allowed by the timeout value 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: def check_pair(script, instr, outstr, timeout) -> Status:
""" """
Check that a Bash script outputs a given string when given a input string. 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( process = Popen(
[ [
"/bin/bash", "--restricted", "-c", "--", "/bin/bash", "-c", "--",
"trap 'kill -9 $(jobs -p) && wait' SIGINT SIGTERM EXIT;\n" "trap 'kill -9 $(jobs -p) && wait' SIGINT SIGTERM EXIT;\n"
+ script, + script,
], ],
stdin=PIPE, stdin=PIPE,
stdout=PIPE, stdout=PIPE,
stderr=DEVNULL, stderr=DEVNULL,
preexec_fn=demote,
) )
try: try: