Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 5,310 Bytes
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
"""Unprivileged pytest entry point. Run only in the credential-free executor."""

from __future__ import annotations

import ctypes
import errno
import json
import os
import resource
import runpy
import sys


def restrict_filesystem_writes() -> None:
    """Allow writes only to this call's workspace and disposable scratch.

    Landlock is inherited across exec and mediates absolute paths, symlinks,
    renames and truncation. A different TMPDIR alone would not protect /tmp or
    /dev/shm. ABI 3 is required for truncate mediation; unsupported kernels fail
    closed before any submitted code is imported.
    """
    libc = ctypes.CDLL(None, use_errno=True)
    abi = libc.syscall(444, ctypes.c_void_p(), 0, 1)
    if abi < 3:
        raise RuntimeError("Execution requires Linux Landlock ABI >= 3")

    class Ruleset(ctypes.Structure):
        _fields_ = [("handled_access_fs", ctypes.c_uint64)]

    class PathRule(ctypes.Structure):
        _pack_ = 1
        _fields_ = [("allowed_access", ctypes.c_uint64), ("parent_fd", ctypes.c_int32)]

    # WRITE_FILE, REMOVE_*, MAKE_*, REFER and TRUNCATE. Reads remain subject to
    # the container's normal permissions, including the private verifier dirs.
    writes = sum(1 << bit for bit in (1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14))
    attributes = Ruleset(writes)
    ruleset = libc.syscall(444, ctypes.byref(attributes), ctypes.sizeof(attributes), 0)
    if ruleset < 0:
        raise RuntimeError("Cannot create execution filesystem boundary")
    try:
        scratch = os.environ.get("TMPDIR")
        if not scratch or not os.path.isabs(scratch):
            raise RuntimeError("Execution scratch directory is missing")
        for path, access in ((os.getcwd(), writes), (scratch, writes), ("/dev/null", 1 << 1)):
            descriptor = os.open(path, os.O_PATH | os.O_CLOEXEC)
            try:
                rule = PathRule(access, descriptor)
                if libc.syscall(445, ruleset, 1, ctypes.byref(rule), 0) != 0:
                    raise RuntimeError("Cannot define execution filesystem boundary")
            finally:
                os.close(descriptor)
        if libc.prctl(38, 1, 0, 0, 0) != 0 or libc.syscall(446, ruleset, 0) != 0:
            raise RuntimeError("Cannot activate execution filesystem boundary")
    finally:
        os.close(ruleset)


def isolate(timeout: int) -> None:
    resource.setrlimit(resource.RLIMIT_CPU, (timeout, timeout + 1))
    resource.setrlimit(resource.RLIMIT_AS, (384 * 1024 * 1024,) * 2)
    resource.setrlimit(resource.RLIMIT_FSIZE, (4 * 1024 * 1024,) * 2)
    resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64))
    resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
    restrict_filesystem_writes()
    # No child process may create sockets, inspect the daemon, change namespaces
    # or detach from the process group. Fail closed when seccomp is unavailable.
    lib = ctypes.CDLL("libseccomp.so.2", use_errno=True)
    lib.seccomp_init.argtypes = [ctypes.c_uint32]
    lib.seccomp_init.restype = ctypes.c_void_p
    lib.seccomp_rule_add.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int, ctypes.c_uint]
    lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p]
    lib.seccomp_load.argtypes = [ctypes.c_void_p]
    lib.seccomp_release.argtypes = [ctypes.c_void_p]
    context = lib.seccomp_init(0x7FFF0000)
    if not context:
        raise RuntimeError("Cannot initialize execution isolation")
    try:
        for name in (
            "socket", "socketpair", "connect", "ptrace", "process_vm_readv", "process_vm_writev",
            "mount", "unshare", "setns", "bpf", "setsid", "setpgid", "fork", "vfork", "clone", "clone3",
            "io_uring_setup", "io_uring_enter", "io_uring_register",
            "shmget", "shmat", "shmdt", "shmctl", "semget", "semop", "semtimedop", "semctl",
            "msgget", "msgsnd", "msgrcv", "msgctl", "mq_open", "mq_unlink", "mq_timedsend",
            "mq_timedreceive", "mq_notify", "mq_getsetattr", "add_key", "request_key", "keyctl",
        ):
            number = lib.seccomp_syscall_resolve_name(name.encode())
            if number >= 0 and lib.seccomp_rule_add(context, 0x00050000 | errno.EPERM, number, 0):
                raise RuntimeError("Cannot install execution isolation rule")
        if lib.seccomp_load(context):
            raise RuntimeError("Cannot activate execution isolation")
    finally:
        lib.seccomp_release(context)


def main() -> None:
    request = json.load(sys.stdin)
    isolate(request["timeout_s"])
    print("CI_EXECUTION_ISOLATED_V1", flush=True)
    # Preserve the upstream pytest arguments; -I and a clean environment prevent
    # package/plugin injection from the trusted service's environment.
    sys.path.insert(0, os.getcwd())
    if request.get("mode", "pytest") == "python":
        command = request["command"]
        if command[0] == "-c":
            sys.argv = ["-c", *command[2:]]
            namespace = {"__name__": "__main__", "__builtins__": __builtins__}
            exec(compile(command[1], "<string>", "exec"), namespace)
        else:
            sys.argv = command
            runpy.run_path(command[0], run_name="__main__")
        return
    import pytest

    raise SystemExit(pytest.main(request["args"]))


if __name__ == "__main__":
    main()