File size: 10,169 Bytes
0520f67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
"""V2 restricted quantum executor; v1 remains frozen in quantum_sandbox.py.

AST screening is combined with nobody UID, cleared environment, process/resource
limits and seccomp denial of filesystem opens, networking and process execution.
Libraries are imported/warmed in the parent before any untrusted code runs.
"""

import ast
import contextlib
import ctypes
import ctypes.util
import errno
import importlib
import io
import multiprocessing as mp
import os
import resource

for variable in ["OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"]:
    os.environ[variable] = "1"

import numpy as np

MODULES = {
    "numpy",
    "numpy.linalg",
    "math",
    "cmath",
    "qiskit",
    "qiskit.quantum_info",
    "pennylane",
    "cirq",
}
ATTRIBUTES = set(
    "array asarray zeros ones eye pi sqrt exp sin cos conj conjugate transpose reshape flatten ravel squeeze astype complex64 complex128 float32 float64 norm kron real imag T shape size data QuantumCircuit Statevector from_instruction h x y z ry rx rz cx cz swap s sdg t tdg sx barrier append device qnode state RY RX RZ Rot PhaseShift Identity PauliX PauliY PauliZ Hadamard CNOT CZ SWAP LineQubit range Circuit Simulator simulate final_state_vector H X Y Z CXPowGate ZPowGate XPowGate HPowGate controlled on inverse quantum_info".split()
)
# Documented Cirq gate aliases, independent of any v2 model outputs. They were
# absent from v1's conservative supported API. No isolation rule is relaxed.
ATTRIBUTES.update({"CX", "Rx", "Ry", "Rz"})
BUILTINS = {
    "range": lambda *a: bounded_range(*a),
    "enumerate": enumerate,
    "zip": zip,
    "len": len,
    "list": list,
    "tuple": tuple,
    "float": float,
    "int": int,
    "complex": complex,
    "print": print,
    "abs": abs,
    "sum": sum,
    "min": min,
    "max": max,
    "reversed": reversed,
}
FORBIDDEN = (
    ast.ClassDef,
    ast.AsyncFunctionDef,
    ast.Await,
    ast.While,
    ast.Try,
    ast.With,
    ast.AsyncWith,
    ast.Raise,
    ast.Delete,
    ast.Global,
    ast.Nonlocal,
    ast.Lambda,
    ast.Yield,
    ast.YieldFrom,
    ast.Match,
)
LIB = None


def bounded_range(*args):
    value = range(*args)
    if len(value) > 1024:
        raise ValueError("range limit")
    return value


def screen(program):
    if len(program) > 25000:
        raise ValueError("program length limit")
    tree = ast.parse(program)
    if sum(1 for _ in ast.walk(tree)) > 6000:
        raise ValueError("AST node limit")
    for node in ast.walk(tree):
        if isinstance(node, FORBIDDEN):
            raise ValueError("unsupported syntax: " + type(node).__name__)
        if isinstance(node, ast.Name) and (
            node.id.startswith("_")
            or node.id
            in {
                "eval",
                "exec",
                "compile",
                "open",
                "getattr",
                "setattr",
                "globals",
                "locals",
                "vars",
                "type",
                "object",
                "input",
                "help",
                "breakpoint",
            }
        ):
            raise ValueError("forbidden name")
        if isinstance(node, ast.Attribute) and node.attr not in ATTRIBUTES:
            raise ValueError("unsupported attribute: " + node.attr)
        if isinstance(node, ast.Import):
            if any(a.name not in MODULES or (a.asname or "").startswith("_") for a in node.names):
                raise ValueError("unsupported import")
        if isinstance(node, ast.ImportFrom):
            if (
                node.level
                or node.module not in MODULES
                or any(
                    a.name not in ATTRIBUTES or (a.asname or "").startswith("_") for a in node.names
                )
            ):
                raise ValueError("unsupported from import")
        if isinstance(node, ast.FunctionDef) and node.name.startswith("_"):
            raise ValueError("forbidden function name")
    return tree


def initialize():
    global LIB
    assert os.name == "posix" and os.getuid() == 0, "Linux root parent required for UID isolation"
    # Resolve/load seccomp before restricting filesystem access.
    library = ctypes.util.find_library("seccomp")
    assert library, "libseccomp is required; never fall back to AST-only execution"
    LIB = ctypes.CDLL(library, use_errno=True)
    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_load.argtypes = [ctypes.c_void_p]
    LIB.seccomp_release.argtypes = [ctypes.c_void_p]
    from qiskit import QuantumCircuit
    from qiskit.quantum_info import Statevector
    import pennylane as qml
    import cirq

    qc = QuantumCircuit(2)
    qc.h(0)
    qc.ry(0.3, 1)
    qc.rz(0.17, 0)
    qc.x(0)
    qc.z(1)
    qc.cx(0, 1)
    Statevector.from_instruction(qc)
    device = qml.device("default.qubit", wires=[1, 0])

    @qml.qnode(device)
    def warm():
        qml.Hadamard(0)
        qml.RY(0.3, wires=1)
        qml.RZ(0.17, wires=0)
        qml.PauliX(0)
        qml.PauliZ(1)
        qml.CNOT(wires=[0, 1])
        return qml.state()

    warm()
    qubits = cirq.LineQubit.range(2)
    cirq.Simulator(dtype=np.complex128).simulate(
        cirq.Circuit(
            cirq.H(qubits[0]),
            cirq.ry(0.3)(qubits[1]),
            cirq.rz(0.17)(qubits[0]),
            cirq.X(qubits[0]),
            cirq.Z(qubits[1]),
            cirq.CNOT(*qubits),
        ),
        qubit_order=list(reversed(qubits)),
    )
    # Warm Python import machinery and serialization before fork/lockdown.
    for module in MODULES:
        importlib.import_module(module)
    importlib.import_module("socket")
    return dict(
        qiskit=importlib.import_module("qiskit").__version__,
        pennylane=qml.__version__,
        cirq=cirq.__version__,
    )


def lockdown():
    os.environ.clear()
    os.setgroups([])
    os.setgid(65534)
    os.setuid(65534)
    resource.setrlimit(resource.RLIMIT_CPU, (15, 15))
    # Native numeric runtimes reserve large virtual address spaces. Physical
    # memory remains bounded by the HF CPU job container's memory allocation.
    resource.setrlimit(resource.RLIMIT_AS, (16 * 1024**3, 16 * 1024**3))
    resource.setrlimit(resource.RLIMIT_FSIZE, (0, 0))
    resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
    resource.setrlimit(resource.RLIMIT_NPROC, (32, 32))
    libc = ctypes.CDLL(None, use_errno=True)
    assert libc.prctl(38, 1, 0, 0, 0) == 0, "PR_SET_NO_NEW_PRIVS failed"
    policy = LIB.seccomp_init(0x7FFF0000)  # SCMP_ACT_ALLOW
    assert policy
    deny = 0x00050000 | errno.EPERM  # SCMP_ACT_ERRNO(EPERM)
    for name in [
        "open",
        "openat",
        "openat2",
        "creat",
        "socket",
        "socketpair",
        "connect",
        "accept",
        "accept4",
        "bind",
        "listen",
        "sendto",
        "sendmsg",
        "execve",
        "execveat",
        "ptrace",
        "process_vm_readv",
        "process_vm_writev",
        "mount",
        "umount2",
        "bpf",
        "userfaultfd",
    ]:
        syscall = LIB.seccomp_syscall_resolve_name(name.encode())
        if syscall >= 0:
            assert LIB.seccomp_rule_add(policy, deny, syscall, 0) == 0, name
    assert LIB.seccomp_load(policy) == 0, "seccomp load failed"
    LIB.seccomp_release(policy)


def safe_import(name, globals=None, locals=None, fromlist=(), level=0):
    if name not in MODULES or level:
        raise ImportError("module not allowed")
    module = importlib.import_module(name)
    return module if fromlist else importlib.import_module(name.split(".")[0])


def worker(program, qubits, connection, mode):
    try:
        lockdown()
        if mode == "isolation_check":
            import socket

            file_blocked = network_blocked = False
            try:
                open("/etc/hostname").read()
            except PermissionError:
                file_blocked = True
            try:
                socket.socket()
            except PermissionError:
                network_blocked = True
            connection.send(
                dict(
                    file_opens_blocked=file_blocked,
                    network_blocked=network_blocked,
                    uid=os.getuid(),
                    environment_empty=not os.environ,
                )
            )
            return
        tree = screen(program)
        safe = dict(BUILTINS, __import__=safe_import)
        namespace = {"__builtins__": safe}
        with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
            exec(compile(tree, "<restricted-quantum>", "exec"), namespace, namespace)
        value = np.asarray(namespace["state"], dtype=np.complex128).reshape(-1)
        assert value.shape == (2**qubits,) and np.isfinite(value).all()
        connection.send(
            dict(
                status="executed",
                real=value.real.tolist(),
                imag=value.imag.tolist(),
                norm=float(np.linalg.norm(value)),
            )
        )
    except BaseException as error:
        connection.send(
            dict(status="rejected_or_error", error=type(error).__name__, detail=str(error)[:300])
        )
    finally:
        connection.close()


def run(program, qubits, mode="program"):
    assert 1 <= qubits <= 8
    ctx = mp.get_context("fork")
    receive, send = ctx.Pipe(duplex=False)
    process = ctx.Process(target=worker, args=(program, qubits, send, mode))
    process.start()
    send.close()
    if receive.poll(20):
        try:
            result = receive.recv()
        except EOFError:
            result = dict(status="worker_exit", exitcode=process.exitcode)
    else:
        result = dict(status="timeout")
    process.join(1)
    if process.is_alive():
        process.kill()
        process.join(2)
    receive.close()
    return result