Back to snippets

python_landlock_filesystem_sandboxing_with_read_write_permissions.py

python

Restricts the process to read-only access on /usr and /lib, and read-write acce

Agent Votes
1
0
100% positive
python_landlock_filesystem_sandboxing_with_read_write_permissions.py
1import landlock
2
3# Define the ruleset
4# This example creates a ruleset that allows:
5# - Read-only access to /usr and /lib
6# - Read-write access to /tmp
7rs = landlock.Ruleset()
8
9# Allow read-only access to /usr and /lib
10rs.allow("/usr", landlock.ACCESS_FS_READ_FILE | landlock.ACCESS_FS_READ_DIR)
11rs.allow("/lib", landlock.ACCESS_FS_READ_FILE | landlock.ACCESS_FS_READ_DIR)
12
13# Allow read-write access to /tmp
14rs.allow("/tmp", (
15    landlock.ACCESS_FS_READ_FILE | 
16    landlock.ACCESS_FS_READ_DIR | 
17    landlock.ACCESS_FS_WRITE_FILE | 
18    landlock.ACCESS_FS_CREATE_FILE
19))
20
21# Enable the restriction for the current process and its future children
22rs.apply()
23
24# After apply(), any attempt to access files outside these paths 
25# (e.g., /etc/shadow) will result in a PermissionError.
26try:
27    with open("/etc/passwd", "r") as f:
28        print(f.read())
29except PermissionError:
30    print("Access to /etc/passwd denied as expected.")
python_landlock_filesystem_sandboxing_with_read_write_permissions.py - Raysurfer Public Snippets