File size: 6,663 Bytes
6d6b4b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env python3
"""Run analysis Python while denying network and child-process escape paths."""

from __future__ import annotations

import ctypes
import errno
import os
import runpy
import sys
from pathlib import Path


BLOCKED_AUDIT_PREFIXES = ("socket.", "subprocess.")
BLOCKED_AUDIT_EVENTS = {
    "os.fork",
    "os.forkpty",
    "os.exec",
    "os.posix_spawn",
    "os.spawn",
    "os.system",
}
WORKSPACE = Path(os.getenv("BIOEVAL_WORKSPACE", "/app")).resolve()
SYSTEM_READ_ROOTS = tuple(
    Path(path).resolve()
    for path in (
        "/usr",
        "/bin",
        "/lib",
        "/lib64",
        "/etc",
        sys.prefix,
        sys.base_prefix,
    )
    if Path(path).exists()
)

SCMP_ACT_ALLOW = 0x7FFF0000
SCMP_ACT_ERRNO = 0x00050000
SCMP_CMP_MASKED_EQ = 7
CLONE_THREAD = 0x00010000
BLOCKED_SYSCALLS = (
    "socket",
    "socketpair",
    "connect",
    "bind",
    "listen",
    "accept",
    "accept4",
    "sendto",
    "sendmsg",
    "sendmmsg",
    "recvfrom",
    "recvmsg",
    "recvmmsg",
    "shutdown",
    "fork",
    "vfork",
    "execve",
    "execveat",
    "ptrace",
    "process_vm_readv",
    "process_vm_writev",
    "mount",
    "umount2",
    "pivot_root",
    "chroot",
    "setns",
    "unshare",
    "bpf",
    "keyctl",
    "add_key",
    "request_key",
    "userfaultfd",
)


class ScmpArgCmp(ctypes.Structure):
    _fields_ = [
        ("arg", ctypes.c_uint),
        ("op", ctypes.c_uint),
        ("datum_a", ctypes.c_uint64),
        ("datum_b", ctypes.c_uint64),
    ]


def install_seccomp_filter() -> None:
    """Kernel-enforce no network, child process, namespace, or tracing syscalls."""
    try:
        seccomp = ctypes.CDLL("libseccomp.so.2", use_errno=True)
    except OSError as exc:
        raise RuntimeError("libseccomp is required for restricted Python") from exc
    seccomp.seccomp_init.argtypes = [ctypes.c_uint32]
    seccomp.seccomp_init.restype = ctypes.c_void_p
    seccomp.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p]
    seccomp.seccomp_syscall_resolve_name.restype = ctypes.c_int
    seccomp.seccomp_rule_add.argtypes = [
        ctypes.c_void_p,
        ctypes.c_uint32,
        ctypes.c_int,
        ctypes.c_uint,
    ]
    seccomp.seccomp_rule_add.restype = ctypes.c_int
    seccomp.seccomp_rule_add_array.argtypes = [
        ctypes.c_void_p,
        ctypes.c_uint32,
        ctypes.c_int,
        ctypes.c_uint,
        ctypes.POINTER(ScmpArgCmp),
    ]
    seccomp.seccomp_rule_add_array.restype = ctypes.c_int
    seccomp.seccomp_load.argtypes = [ctypes.c_void_p]
    seccomp.seccomp_load.restype = ctypes.c_int
    seccomp.seccomp_release.argtypes = [ctypes.c_void_p]

    context = seccomp.seccomp_init(SCMP_ACT_ALLOW)
    if not context:
        raise RuntimeError("could not initialize seccomp")
    try:
        deny = SCMP_ACT_ERRNO | errno.EPERM
        for name in BLOCKED_SYSCALLS:
            number = seccomp.seccomp_syscall_resolve_name(name.encode())
            if number < 0:
                continue
            result = seccomp.seccomp_rule_add(context, deny, number, 0)
            if result != 0:
                raise OSError(-result, os.strerror(-result))
        clone_number = seccomp.seccomp_syscall_resolve_name(b"clone")
        if clone_number >= 0:
            comparison = ScmpArgCmp(0, SCMP_CMP_MASKED_EQ, CLONE_THREAD, 0)
            result = seccomp.seccomp_rule_add_array(
                context, deny, clone_number, 1, ctypes.byref(comparison)
            )
            if result != 0:
                raise OSError(-result, os.strerror(-result))
        clone3_number = seccomp.seccomp_syscall_resolve_name(b"clone3")
        if clone3_number >= 0:
            result = seccomp.seccomp_rule_add(
                context, SCMP_ACT_ERRNO | errno.ENOSYS, clone3_number, 0
            )
            if result != 0:
                raise OSError(-result, os.strerror(-result))
        result = seccomp.seccomp_load(context)
        if result != 0:
            raise OSError(-result, os.strerror(-result))
    finally:
        seccomp.seccomp_release(context)


def _inside(path: Path, root: Path) -> bool:
    try:
        path.relative_to(root)
        return True
    except ValueError:
        return False


def _check_open(args: tuple[object, ...]) -> None:
    if not args or isinstance(args[0], int):
        return
    path = Path(os.fspath(args[0]))
    resolved = (Path.cwd() / path if not path.is_absolute() else path).resolve()
    mode = args[1] if len(args) > 1 else None
    flags = args[2] if len(args) > 2 and isinstance(args[2], int) else 0
    write_requested = (
        isinstance(mode, str) and any(marker in mode for marker in ("w", "a", "x", "+"))
    ) or flags & os.O_ACCMODE != os.O_RDONLY or bool(
        flags & (os.O_CREAT | os.O_TRUNC | os.O_APPEND)
    )
    if write_requested:
        if not _inside(resolved, WORKSPACE):
            raise PermissionError("Analysis Python may only write inside /app.")
        return
    readable = _inside(resolved, WORKSPACE) or any(
        _inside(resolved, root) for root in SYSTEM_READ_ROOTS
    )
    if resolved in {Path("/dev/null"), Path("/dev/urandom"), Path("/dev/random")}:
        readable = True
    if not readable:
        raise PermissionError("Analysis Python may only read workspace and runtime files.")


def deny_unsafe_runtime(event: str, args: tuple[object, ...]) -> None:
    if event == "open":
        _check_open(args)
    elif event in BLOCKED_AUDIT_EVENTS or event.startswith(BLOCKED_AUDIT_PREFIXES):
        raise PermissionError(
            "Network and child-process access are disabled in analysis Python; "
            "use the guarded research tools."
        )


def main(argv: list[str] | None = None) -> int:
    args = list(sys.argv[1:] if argv is None else argv)
    if not args:
        raise SystemExit("restricted Python requires -c, -m, or a script path")
    install_seccomp_filter()
    sys.addaudithook(deny_unsafe_runtime)
    if args[0] == "-c":
        if len(args) < 2:
            raise SystemExit("-c requires code")
        sys.argv = ["-c", *args[2:]]
        namespace = {"__name__": "__main__", "__file__": "<string>"}
        exec(compile(args[1], "<string>", "exec"), namespace, namespace)
        return 0
    if args[0] == "-m":
        if len(args) < 2:
            raise SystemExit("-m requires a module")
        sys.argv = [args[1], *args[2:]]
        runpy.run_module(args[1], run_name="__main__", alter_sys=True)
        return 0
    sys.argv = [args[0], *args[1:]]
    runpy.run_path(args[0], run_name="__main__")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())