File size: 3,831 Bytes
d086025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import base64
import ctypes
import fcntl
import json
import os
import select
import socket
import struct
import sys
from pathlib import Path

SOCKET_PATH = os.environ.get("PROGRAMGEN_REFERENCE_ORACLE_SOCKET", '/run/programgen-reference-oracle/oracle.sock')
_ENV_ALLOWLIST = {"LANG", "LC_ALL"}
_POLICY_DENIED = "programgen policy denied: debugging or wrapping /reference/executable is not allowed\n"
_PR_SET_DUMPABLE = 4
_PR_SET_NO_NEW_PRIVS = 38


def _read_exact(sock, size):
    chunks = []
    remaining = size
    while remaining:
        chunk = sock.recv(remaining)
        if not chunk:
            raise RuntimeError("oracle connection closed early")
        chunks.append(chunk)
        remaining -= len(chunk)
    return b"".join(chunks)


def _encode_arg(value):
    return base64.b64encode(os.fsencode(value)).decode("ascii")


def _prctl(option, arg2):
    try:
        libc = ctypes.CDLL(None)
        libc.prctl(option, arg2, 0, 0, 0)
    except Exception:
        pass


def _has_blocked_loader_environment():
    return any(
        key.startswith("LD_") or key.startswith("DYLD_")
        for key in os.environ
    )


def _tracer_pid():
    try:
        for line in Path("/proc/self/status").read_text(errors="replace").splitlines():
            if line.startswith("TracerPid:"):
                return int(line.split(":", 1)[1].strip())
    except Exception:
        return 0
    return 0


def _harden_process():
    _prctl(_PR_SET_NO_NEW_PRIVS, 1)
    _prctl(_PR_SET_DUMPABLE, 0)
    if _has_blocked_loader_environment() or _tracer_pid() > 0:
        sys.stderr.write(_POLICY_DENIED)
        return False
    return True


def _read_available_stdin():
    try:
        fd = sys.stdin.buffer.fileno()
    except (AttributeError, OSError, ValueError):
        return b""

    try:
        readable, _, _ = select.select([fd], [], [], 0)
    except (OSError, ValueError):
        return b""
    if not readable:
        return b""

    chunks = []
    try:
        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    except OSError:
        return b""

    try:
        fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
        while True:
            try:
                chunk = os.read(fd, 65536)
            except BlockingIOError:
                break
            if not chunk:
                break
            chunks.append(chunk)
    finally:
        try:
            fcntl.fcntl(fd, fcntl.F_SETFL, flags)
        except OSError:
            pass

    return b"".join(chunks)


def main():
    if not _harden_process():
        return 126

    env = {
        key: value
        for key, value in os.environ.items()
        if key in _ENV_ALLOWLIST
    }
    request = {
        "argv_b64": [_encode_arg(arg) for arg in sys.argv],
        "cwd": os.getcwd(),
        "env": env,
        "stdin_b64": base64.b64encode(_read_available_stdin()).decode("ascii"),
    }
    payload = json.dumps(request, separators=(",", ":")).encode("utf-8")

    sock = None
    try:
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.connect(SOCKET_PATH)
        sock.sendall(struct.pack(">Q", len(payload)) + payload)
        size = struct.unpack(">Q", _read_exact(sock, 8))[0]
        response = json.loads(_read_exact(sock, size).decode("utf-8"))
    except Exception as exc:
        sys.stderr.write(f"programgen reference oracle unavailable: {exc}\n")
        return 127
    finally:
        if sock is not None:
            try:
                sock.close()
            except Exception:
                pass

    sys.stdout.buffer.write(base64.b64decode(response.get("stdout_b64", "")))
    sys.stderr.buffer.write(base64.b64decode(response.get("stderr_b64", "")))
    return int(response.get("return_code", 1))


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