Repository navigation
Expand file tree
/
Copy pathjail.py
More file actions
147 lines (107 loc) · 5.39 KB
/
Copy pathjail.py
File metadata and controls
147 lines (107 loc) · 5.39 KB
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
'''
Start a command that is locked into its working directory:
python3 -I jail.py COMMAND [ARGUMENT ...]
All runs belong to the same user, so file permissions separate nothing: without the lock
a program can read and change the folders of all other runs, write into the code of the
server and end the server. Namespaces (firejail, bubblewrap) and separate users need
rights that a container on Heroku does not have. Landlock needs none: a process gives
up rights for itself and for every process it starts.
The command may
- read and execute everything except what lies next to its working directory: the
folders of the other runs,
- write to its working directory, to /dev, to $HOME (server.py sets it to a folder that
all runs share), to the caches in /opt that the Dockerfile opened for all users
(chmod a+rwX) and to /tmp and /var/tmp,
- signal only processes of its own run (Linux 6.12). That also keeps it out of
/proc/<pid> of the server and of other runs.
So /tmp stays what it is on every system, a place for all: the JVM and other tools write
there whatever TMPDIR says. That is why the folders of the runs are not in /tmp
(CODERUNNER_RUNS). If they are, /tmp is closed, and those tools fail. Tools that follow
TMPDIR keep their temporary files to themselves, in .tmp of the working directory.
The network stays open. Landlock limits no CPU time, memory or disk space.
Without Landlock (Linux before 5.13, or switched off) the command starts unlocked.
server.py reports at its start what the lock covers.
'''
import ctypes
import os
import stat
import struct
import sys
# Rights on files and folders, one bit each. Later versions of Landlock added rights:
# 2 moving files between folders, 3 truncating, 5 ioctl on devices.
EXECUTE, WRITE_FILE, READ_FILE, READ_DIR = 1 << 0, 1 << 1, 1 << 2, 1 << 3
RIGHTS_SINCE = {1: (1 << 13) - 1, 2: 1 << 13, 3: 1 << 14, 5: 1 << 15}
FILE_RIGHTS = EXECUTE | WRITE_FILE | READ_FILE | 1 << 14 | 1 << 15 # for what is not a folder
SCOPES = 3 # version 6: no abstract unix sockets and no signals to the outside
# numbers of the system calls, the same on every architecture
CREATE_RULESET, ADD_RULE, RESTRICT_SELF = 444, 445, 446
libc = ctypes.CDLL(None, use_errno=True)
def syscall(number: int, *arguments) -> int:
result = libc.syscall(ctypes.c_long(number), *[
argument if isinstance(argument, bytes) or argument is None else ctypes.c_long(argument)
for argument in arguments])
if result < 0:
raise OSError(ctypes.get_errno(), "Landlock: " + os.strerror(ctypes.get_errno()))
return result
def version() -> int:
'''Version of Landlock that the kernel offers, 0 without it.'''
try:
return syscall(CREATE_RULESET, None, 0, 1)
except OSError:
return 0
def lock(folder: str, abi: int = 0) -> int:
'''
Give up every right outside of `folder` that the list above does not name, for this
process and all it starts. Returns the version of Landlock in use, 0 if there is none.
A lower `abi` leaves out what later versions added (for tests).
'''
abi = abi or version()
if not abi:
return 0
handled = 0
for since, rights in RIGHTS_SINCE.items():
if abi >= since:
handled |= rights
# handled rights on files, on the network (none: it stays open) and the scopes
attributes = struct.pack("QQQ", handled, 0, SCOPES if abi >= 6 else 0)
ruleset = syscall(CREATE_RULESET, attributes, len(attributes), 0)
folder = os.path.realpath(folder)
parts = folder.strip("/").split("/")
if len(parts) < 2:
raise OSError("no lock for " + folder + ", the folder of a run has to be inside of another one")
# readable: on the way down to the folder that holds the runs, everything next to that
# way. The other entries of that last folder, the other runs, are left out.
readable, path = [], "/"
for part in parts[:-1]:
readable += [os.path.join(path, name) for name in os.listdir(path) if name != part]
path = os.path.join(path, part)
# writable: a folder above the own one would open the other runs again
writable = [folder, "/dev"]
writable += [path for path in (os.path.realpath(os.environ.get("HOME") or "/"), "/tmp", "/var/tmp")
if not (folder + "/").startswith(path.rstrip("/") + "/")]
if os.path.isdir("/opt"):
writable += [entry.path for entry in os.scandir("/opt") if entry.is_dir() and entry.stat().st_mode & stat.S_IWOTH]
rules = [(path, EXECUTE | READ_FILE | READ_DIR) for path in readable] + [(path, handled) for path in writable]
for path, rights in rules:
try:
descriptor = os.open(path, os.O_PATH | os.O_CLOEXEC)
except OSError:
continue
if not stat.S_ISDIR(os.fstat(descriptor).st_mode):
rights &= FILE_RIGHTS
if rights & handled:
syscall(ADD_RULE, ruleset, 1, struct.pack("=Qi", rights & handled, descriptor), 0)
os.close(descriptor)
libc.prctl(38, 1, 0, 0, 0) # PR_SET_NO_NEW_PRIVS, a condition of Landlock
syscall(RESTRICT_SELF, ruleset, 0)
os.close(ruleset)
return abi
if __name__ == "__main__":
temporary = os.path.join(os.getcwd(), ".tmp")
os.makedirs(temporary, exist_ok=True)
os.environ["TMPDIR"] = temporary
lock(os.getcwd())
try:
os.execvp(sys.argv[1], sys.argv[1:])
except OSError as error:
sys.exit("%s: %s" % (sys.argv[1], error.strerror))