"""Trusted worker for one untrusted Python execution. Linux/root setup is required. The parent sends a JSON payload through stdin. The worker NEVER reads credentials. All allowed stdlib modules are loaded before entering an empty chroot. It drops supplementary groups and uid/gid, sets no-new-privileges, applies seccomp and resource limits, and only then executes the submitted code. Nothing is mounted inside the jail. This is a restricted stdlib harness, not a general Docker runner. """ import sys import os import io import json import ctypes import resource # Preload the limited, dependency-free Python runtime before chroot. import math import bisect import heapq import collections import collections.abc import functools import itertools import operator import re import string import statistics import random import typing import fractions import decimal import socket # Used only by the trusted seccomp self-test; candidates cannot import it. def install_seccomp(lib): lib.seccomp_init.argtypes = [ctypes.c_uint32] lib.seccomp_init.restype = ctypes.c_void_p lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] lib.seccomp_syscall_resolve_name.restype = ctypes.c_int lib.seccomp_rule_add.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int, ctypes.c_uint] lib.seccomp_rule_add.restype = ctypes.c_int lib.seccomp_load.argtypes = [ctypes.c_void_p] lib.seccomp_load.restype = ctypes.c_int lib.seccomp_release.argtypes = [ctypes.c_void_p] ctx = lib.seccomp_init(0x7fff0000) # SCMP_ACT_ALLOW if not ctx: raise RuntimeError('seccomp_init failed') denied = ( 'socket socketpair connect bind listen accept accept4 sendto sendmsg ' 'recvfrom recvmsg sendmmsg recvmmsg ' 'clone clone3 fork vfork execve execveat ptrace process_vm_readv process_vm_writev ' 'kill tkill tgkill pidfd_open pidfd_send_signal ' 'mount umount2 pivot_root chroot unshare setns open_by_handle_at name_to_handle_at ' 'mknod mknodat bpf perf_event_open userfaultfd keyctl add_key request_key ' 'reboot kexec_load kexec_file_load init_module finit_module delete_module ' 'io_uring_setup io_uring_enter io_uring_register ' 'setuid setgid setreuid setregid setresuid setresgid setfsuid setfsgid setgroups ' 'capset setrlimit prlimit64' ).split() try: for name in denied: nr = lib.seccomp_syscall_resolve_name(name.encode()) if nr >= 0 and lib.seccomp_rule_add(ctx, 0x00050001, nr, 0) != 0: # EPERM raise RuntimeError('Failed to deny syscall: ' + name) if lib.seccomp_load(ctx) != 0: raise RuntimeError('seccomp_load failed') finally: lib.seccomp_release(ctx) def main(): payload = json.loads(sys.stdin.buffer.read()) jail = sys.argv[1] code = compile(payload['code'], '', 'exec') seccomp = ctypes.CDLL('libseccomp.so.2', use_errno=True) libc = ctypes.CDLL(None, use_errno=True) os.environ.clear() os.umask(0o077) # Enter an EMPTY, root-owned directory. No credential, host file, device, # executable, /proc, network socket or writable directory is exposed. os.chroot(jail) os.chdir('/') os.setgroups([]) os.setgid(65534) os.setuid(65534) resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) resource.setrlimit(resource.RLIMIT_CPU, (3, 4)) resource.setrlimit(resource.RLIMIT_AS, (256 * 1024**2, 256 * 1024**2)) resource.setrlimit(resource.RLIMIT_FSIZE, (4 * 1024**2, 4 * 1024**2)) resource.setrlimit(resource.RLIMIT_NOFILE, (16, 16)) resource.setrlimit(resource.RLIMIT_NPROC, (0, 0)) if libc.prctl(38, 1, 0, 0, 0) != 0: # PR_SET_NO_NEW_PRIVS raise RuntimeError('no_new_privs failed') install_seccomp(seccomp) sys.argv = ['solution.py'] text = payload.get('input', '') sys.stdin = io.TextIOWrapper(io.BytesIO(text.encode()), encoding='utf-8') sys.__stdin__ = sys.stdin scope = {'__name__': '__main__', '__file__': '/solution.py'} exec(code, scope) if payload['mode'] == 'call': entry = payload['entry_point'] if entry.startswith('Solution.'): fn = getattr(scope['Solution'](), entry.split('.', 1)[1]) else: fn = scope[entry] result = fn(*payload['args']) sys.stdout.write(json.dumps(result, ensure_ascii=False, allow_nan=False)) sys.stdout.write('\n') if __name__ == '__main__': main()