Landlock for Python

1.0.0.dev5 · active · verified Sat Apr 11

Landlock for Python is a library providing a Python interface to the Landlock Linux Security Module (LSM). It enables developers to apply rule-based filesystem access restrictions to Python code, enhancing application security by limiting what an unprivileged process can access. Currently at version 1.0.0.dev5, its release cadence is in active development, with periodic updates as the Landlock kernel module itself evolves.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a Landlock ruleset to restrict filesystem access. It allows reading the current directory and executing `ls` and `cat` from `/usr/bin`, while implicitly denying access to all other paths, such as `/etc/passwd`. The `apply()` method enforces these rules on the current thread and its children.

import os
from landlock import Ruleset, LandlockError

def main():
    # Create a ruleset, by default it disallows all filesystem access
    rs = Ruleset()
    
    # Explicitly allow read access to the current directory and its contents
    # and execute access to /usr/bin for common commands
    rs.allow_read('.')
    rs.allow_execute('/usr/bin/ls')
    rs.allow_execute('/usr/bin/cat')
    
    try:
        # Apply the Landlock ruleset to the current thread
        rs.apply()
        print("Landlock rules applied. Trying to access allowed paths...")
        
        # This should succeed
        print(f"Current directory listing: {os.listdir('.')}")
        os.system("ls -l .")
        
        print("\nTrying to access a disallowed path (/etc/passwd)...")
        # This should fail with a PermissionError (or similar LandlockError)
        try:
            with open('/etc/passwd', 'r') as f:
                _ = f.read()
            print("Accessed /etc/passwd (unexpectedly succeeded)")
        except LandlockError as e:
            print(f"Caught expected LandlockError: {e}")
        except PermissionError as e:
            print(f"Caught expected PermissionError: {e}")
        
    except LandlockError as e:
        print(f"Landlock is not available or failed to apply rules: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == '__main__':
    main()

view raw JSON →