### Complete Go-Landlock Example Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md A full example demonstrating how to apply filesystem and network restrictions early in a Go program using Landlock ABI V8 and `.BestEffort()`. ```go package main import ( "github.com/landlock-lsm/go-landlock/landlock" "log" ) func main() { // Apply restrictions early err := landlock.V8.BestEffort().Restrict( // Filesystem rules landlock.RODirs("/usr", "/bin", "/lib"), landlock.RWDirs("/tmp"), // Network rules landlock.ConnectTCP(53), landlock.ConnectTCP(443), ) if err != nil { log.Fatal(err) } // Rest of program runs sandboxed fmt.Println("Sandboxed!") } ``` -------------------------------- ### Usage Example for ScopedSet Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/types.md Shows how to create a ScopedSet to restrict both signals and abstract socket connections, then use it to initialize a Landlock configuration. ```go import ( "github.com/landlock-lsm/go-landlock/landlock" llsyscall "github.com/landlock-lsm/go-landlock/landlock/syscall" ) // Restrict both signals and abstract sockets scoped := landlock.ScopedSet( llsyscall.ScopeAbstractUnixSocket | llsyscall.ScopeSignal, ) cfg, err := landlock.NewConfig(scoped) ``` -------------------------------- ### Usage Example for NetRule Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/types.md Demonstrates how to create a NetRule for connecting to a TCP port and apply it using Landlock V4. ```go import "github.com/landlock-lsm/go-landlock/landlock" rule := landlock.ConnectTCP(53) err := landlock.V4.BestEffort().RestrictNet(rule) ``` -------------------------------- ### Usage Example for AccessNetSet Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/types.md Demonstrates how to create an AccessNetSet to allow both TCP bind and connect operations, then use it to create a new Landlock configuration. ```go import ( "github.com/landlock-lsm/go-landlock/landlock" llsyscall "github.com/landlock-lsm/go-landlock/landlock/syscall" ) // Allow both TCP operations netRights := landlock.AccessNetSet( llsyscall.AccessNetBindTCP | llsyscall.AccessNetConnectTCP, ) cfg, err := landlock.NewConfig(netRights) ``` -------------------------------- ### Usage Example for FSRule Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/types.md Demonstrates creating an FSRule for read-write access to a directory, adding the 'refer' right, and ignoring missing paths. Then, it applies this rule using Landlock V8. ```go import "github.com/landlock-lsm/go-landlock/landlock" rule := landlock.RWDirs("/tmp"). WithRefer(). IgnoreIfMissing() err := landlock.V8.BestEffort().RestrictPaths(rule) ``` -------------------------------- ### Restrict Paths with Error Handling Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/README.md Apply read-only directory restrictions. This example shows how to handle potential errors, such as the path not existing. ```go // Fail if path doesn't exist err := landlock.V8.RestrictPaths( landlock.RODirs("/etc/config"), ) ``` -------------------------------- ### Simple Filesystem Sandboxing with go-landlock Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/architecture-and-patterns.md This example demonstrates how to apply basic filesystem restrictions early in your program's execution. It uses the V8 ABI version with best-effort downgrading and restricts read-only access to /usr and /bin, and read-write access to /tmp. Ensure Landlock is available on your system; otherwise, the call will succeed without applying restrictions. ```go import ( "github.com/landlock-lsm/go-landlock/landlock" "log" ) func main() { // Early in main(), after initialization err := landlock.V8.BestEffort().RestrictPaths( landlock.RODirs("/usr", "/bin"), landlock.RWDirs("/tmp"), ) if err != nil { log.Fatal(err) } // Rest of program runs sandboxed } ``` -------------------------------- ### Example: Restrict File Execution and Reading Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/syscall-constants.md Constructs a Landlock configuration to restrict only file execution and reading using filesystem access right constants. Helper functions like ROKit() are generally recommended over manual set construction. ```go import ( "github.com/landlock-lsm/go-landlock/landlock" llsyscall "github.com/landlock-lsm/go-landlock/landlock/syscall" ) // Restrict only file execution and reading cfg, err := landlock.NewConfig( landlock.AccessFSSet( llsyscall.AccessFSExecute | llsyscall.AccessFSReadFile, ), ) ``` -------------------------------- ### Apply Best Effort Restrictions with V8 Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/configuration.md This example demonstrates using `BestEffort()` with V8 to apply the highest compatible Landlock restrictions supported by the kernel. It gracefully degrades to lower ABI versions or no enforcement if Landlock is not supported or features are missing. ```go import "github.com/landlock-lsm/go-landlock/landlock" // This works correctly on: // - Kernel with V8 support: applies full V8 restrictions // - Kernel with V6 support: applies V6 restrictions (no truncate or IOCTL) // - Kernel with V4 support: applies V4 restrictions (no IPC scope) // - Kernel with no Landlock support: succeeds with no restrictions err := landlock.V8.BestEffort().RestrictPaths( landlock.RODirs("/usr", "/bin"), landlock.RWDirs("/tmp"), ) if err != nil { // Handle unexpected errors (path not found, etc.) log.Fatal(err) } ``` -------------------------------- ### Per-Call Error Reporting with BestEffort Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/errors.md This example demonstrates how to handle potential errors on a per-call basis when using BestEffort(), logging a warning if an unexpected error occurs, as BestEffort() typically suppresses errors. ```go import "github.com/landlock-lsm/go-landlock/landlock" rules := []landlock.Rule{ landlock.RODirs("/usr", "/bin"), } // With BestEffort, you can always succeed even on unsupported kernels if err := landlock.V8.BestEffort().RestrictPaths(rules...); err != nil { // Handle unexpected errors log.Printf("Warning: Landlock may not be fully active: %v", err) } ``` -------------------------------- ### Custom Access Rights for Filesystem Rules Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/architecture-and-patterns.md Define custom access rights for filesystem rules, allowing only specific operations like reading and executing without directory operations. This example uses V8 ABI and BestEffort mode. ```go import ( "github.com/landlock-lsm/go-landlock/landlock" llsyscall "github.com/landlock-lsm/go-landlock/landlock/syscall" ) // Only allow reading and executing, no directory operations rule := landlock.PathAccess( llsyscall.AccessFSExecute | llsyscall.AccessFSReadFile, "/usr/bin", ) err := landlock.V8.BestEffort().RestrictPaths(rule) ``` -------------------------------- ### Example: Restrict TCP Binding and Connection Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/syscall-constants.md Constructs a Landlock configuration to restrict both TCP binding and connection operations using network access right constants. Helper functions like BindTCP() and ConnectTCP() are recommended. ```go import ( "github.com/landlock-lsm/go-landlock/landlock" llsyscall "github.com/landlock-lsm/go-landlock/landlock/syscall" ) cfg, err := landlock.NewConfig( landlock.AccessNetSet( llsyscall.AccessNetBindTCP | llsyscall.AccessNetConnectTCP, ), ) ``` -------------------------------- ### Logging Configuration for Process and Subdomains Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/architecture-and-patterns.md Configure Landlock logging behavior to disable logging for the originating process and suppress logs for subdomains. This example uses V7 ABI and BestEffort mode. ```go cfg := landlock.V7.BestEffort(). DisableLoggingForOriginatingProcess(). // Script interpreter mode DisableLoggingForSubdomains() // Suppress nested logs err := cfg.Restrict( landlock.RODirs("/usr", "/bin"), ) ``` -------------------------------- ### Example: Restrict IPC Scope for Sockets and Signals Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/syscall-constants.md Constructs a Landlock configuration to restrict abstract UNIX domain sockets and signals using IPC scope constants. The RestrictScoped() method is generally recommended over manual set construction. ```go import ( "github.com/landlock-lsm/go-landlock/landlock" llsyscall "github.com/landlock-lsm/go-landlock/landlock/syscall" ) cfg, err := landlock.NewConfig( landlock.ScopedSet( llsyscall.ScopeAbstractUnixSocket | llsyscall.ScopeSignal, ), ) ``` -------------------------------- ### Configure Landlock Logging Behavior with V7 Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/configuration.md This example shows how to configure Landlock's audit logging behavior using V7. It disables logging for the originating process and its direct children, and also suppresses logs from nested Landlock domains, suitable for script interpreters or container runtimes. ```go import "github.com/landlock-lsm/go-landlock/landlock" cfg := landlock.V7.BestEffort(). DisableLoggingForOriginatingProcess(). // Script interpreter mode DisableLoggingForSubdomains(). // Suppress nested domain logs Restrict(landlock.RODirs("/usr", "/bin")) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Preset Configurations (V1-V8) Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/config-and-restrict.md Provides preset Config values for each Landlock ABI version. Higher ABI versions support restricting more operations. These can be used as starting points for restrictions. ```APIDOC ## Preset Configurations (V1-V8) Provides preset `Config` values for each Landlock ABI version. ### V1, V2, V3, V4, V5, V6, V7, V8 ```go var ( V1 Config // Landlock V1 support (basic file operations) V2 Config // Landlock V2 support (V1 + file reparenting) V3 Config // Landlock V3 support (V2 + file truncation) V4 Config // Landlock V4 support (V3 + networking) V5 Config // Landlock V5 support (V4 + ioctl on device files) V6 Config // Landlock V6 support (V5 + IPC scopes) V7 Config // Landlock V7 support (V6 + logging support) V8 Config // Landlock V8 support (V7 + thread synchronization) ) ``` **Import path:** `github.com/landlock-lsm/go-landlock/landlock` **Description:** Preset `Config` values for each Landlock ABI version. The higher the ABI version, the more operations Landlock can restrict. Use these as starting points for your restrictions by calling methods like `RestrictPaths()` on them. **Usage example:** ```go import "github.com/landlock-lsm/go-landlock/landlock" // Restrict using ABI V8, falling back gracefully on older kernels err := landlock.V8.BestEffort().RestrictPaths( landlock.RODirs("/usr", "/bin"), landlock.RWDirs("/tmp"), ) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Preset Landlock Configurations Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/config-and-restrict.md Preset Config values for each Landlock ABI version. Higher ABI versions allow restricting more operations. Use these as starting points for restrictions. ```go var ( V1 Config // Landlock V1 support (basic file operations) V2 Config // Landlock V2 support (V1 + file reparenting) V3 Config // Landlock V3 support (V2 + file truncation) V4 Config // Landlock V4 support (V3 + networking) V5 Config // Landlock V5 support (V4 + ioctl on device files) V6 Config // Landlock V6 support (V5 + IPC scopes) V7 Config // Landlock V7 support (V6 + logging support) V8 Config // Landlock V8 support (V7 + thread synchronization) ) ``` -------------------------------- ### Create and Use AccessFSSet Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/types.md Shows how to create a custom AccessFSSet by combining specific filesystem access rights using bitwise OR, and then using this set to initialize a new Landlock configuration. ```go import ( "github.com/landlock-lsm/go-landlock/landlock" llsyscall "github.com/landlock-lsm/go-landlock/landlock/syscall" ) // Create a set containing only execute and read rights readExec := landlock.AccessFSSet( llsyscall.AccessFSExecute | llsyscall.AccessFSReadFile, ) cfg, err := landlock.NewConfig(readExec) ``` -------------------------------- ### Create Landlock Config Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/types.md Demonstrates creating a Landlock configuration using a preset constant like V8 and applying best-effort degradation, or by constructing a new config with custom filesystem access rights. ```go import "github.com/landlock-lsm/go-landlock/landlock" // Using preset configuration V8 cfg := landlock.V8.BestEffort() // Using custom configuration cfg2, err := landlock.NewConfig(landlock.AccessFSSet(/* ... */)) ``` -------------------------------- ### Search for Landlock ABI Usage Source: https://github.com/landlock-lsm/go-landlock/blob/main/docs/upgrade.md Search your codebase for current Landlock ABI version constants to identify which version is in use. This helps in determining the starting point for the upgrade. ```bash grep -R 'landlock\.V' ``` -------------------------------- ### Filesystem Rule: Allow Device File IOCTL Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Permit `ioctl` operations on device files, requires Landlock ABI V5 or higher. ```go landlock.RWDirs("/dev").WithIoctlDev() // Allow ioctl on device files ``` -------------------------------- ### Filesystem Rule: Allow File Reparenting Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Enable file reparenting (e.g., `mv`, `ln`) between directories, requires Landlock ABI V2 or higher. ```go landlock.RWDirs("/home").WithRefer() // Allow mv/ln between dirs ``` -------------------------------- ### Error Handling: Graceful Degradation Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Use `.BestEffort()` to apply restrictions with the highest possible ABI version, falling back gracefully if unavailable. Errors may still occur for other reasons. ```go err := landlock.V8.BestEffort().RestrictPaths( landlock.RODirs("/usr"), ) if err != nil { log.Fatal(err) // Still might fail on path not found } ``` -------------------------------- ### Filesystem Read-Write Files Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Define files that should be accessible for both reading and writing. ```go landlock.RWFiles("/var/log/app.log") // Read-write files only ``` -------------------------------- ### Create Read-Write Directory Rule Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/rules.md Creates a rule for full read and write access to specified directories and their contents. This rule grants extensive permissions but excludes rights like reparenting or using IOCTL on device files. ```go import "github.com/landlock-lsm/go-landlock/landlock" err := landlock.V8.BestEffort().RestrictPaths( landlock.RWDirs("/tmp", "/home/user/.cache"), ) ``` -------------------------------- ### Configuration Methods in Go-Landlock Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/README.md Provides methods to configure Landlock behavior, including best-effort degradation, and options to control audit logging for the originating process, subprocesses, and nested domains. ```go Config.BestEffort() // Graceful degradation Config.DisableLoggingForOriginatingProcess() // Disable audit logs for this process Config.EnableLoggingForSubprocesses() // Enable audit logs for child processes Config.DisableLoggingForSubdomains() // Disable audit logs for nested domains ``` -------------------------------- ### Create DNS Lookup Rule Library Source: https://github.com/landlock-lsm/go-landlock/blob/main/docs/rule_libraries.md Bundles Landlock rules necessary for basic DNS lookup operations. Use this to encapsulate common DNS access requirements. ```go // DNSLookup bundles the Landlock rules required for basic DNS lookup. func DNSLookup() landlock.Rule { return landlock.CompositeRule( landlock.RODirs("/etc"), landlock.ConnectTCP(53), ) } ``` -------------------------------- ### Import Paths for Go-Landlock Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/README.md Import the main API for general use or the low-level syscall interface for advanced, unstable features. ```go // Main API (recommended) import "github.com/landlock-lsm/go-landlock/landlock" // Low-level syscall interface (unstable, advanced use) import "github.com/landlock-lsm/go-landlock/landlock/syscall" ``` -------------------------------- ### Filesystem Read-Only and Read-Write Directories Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Define directories that should be accessible only for reading or for both reading and writing. ```go landlock.RODirs("/usr", "/bin") // Read-only directories landlock.RWDirs("/tmp", "/home/user") // Read-write directories ``` -------------------------------- ### Sandbox a Web Server Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/README.md Restrict a web server to specific directories for static files and logs, and allow access to web ports and a database port. ```go err := landlock.V8.BestEffort().Restrict( landlock.RODirs("/var/www"), // Static files landlock.RWDirs("/tmp", "/var/log"), // Temporary and log files landlock.BindTCP(80, 443), // Web ports landlock.ConnectTCP(5432), // Database ) ``` -------------------------------- ### Filesystem Rule: Ignore Missing Paths Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Configure a rule to be skipped if the specified path does not exist. ```go landlock.RWDirs("/opt/optional").IgnoreIfMissing() // Skip if not found ``` -------------------------------- ### Constructing Path Access Rules Source: https://github.com/landlock-lsm/go-landlock/blob/main/docs/custom_fs_rules.md Use `landlock.PathAccess` to build Landlock filesystem rules with specific access rights for given paths. Note the interdependency between WRITE_FILE and TRUNCATE access rights. ```go accesses := landlock.PathAccess( landlock.AccessFS(landlock.LANDLOCK_ACCESS_FS_READ_FILE|landlock.LANDLOCK_ACCESS_FS_WRITE_FILE|landlock.LANDLOCK_ACCESS_FS_TRUNCATE), "/etc/passwd", "/etc/shadow", ) ``` -------------------------------- ### Enable Logging for Subprocesses Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/config-and-restrict.md Configure a Landlock Config to enable audit logging for denied accesses that occur after an execve call within the Landlock domain. Use this when all potential executables are expected to comply with restrictions. ```go cfg := landlock.V7.BestEffort(). EnableLoggingForSubprocesses(). RestrictPaths(landlock.RODirs("/usr")) ``` -------------------------------- ### View Landlock ABI Version Documentation Source: https://github.com/landlock-lsm/go-landlock/blob/main/docs/upgrade.md View the documentation for a specific Landlock ABI version to understand changes and upgrade notes. This is crucial for safe adoption of new features. ```bash go doc github.com/landlock-lsm/go-landlock/landlock.V1 ``` -------------------------------- ### Sandbox a Development Environment Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/README.md Configure restrictions for a development environment, allowing read-only access to system libraries and read-write access to project and configuration files, along with access to development server ports. ```go err := landlock.V8.BestEffort().Restrict( landlock.RODirs("/usr", "/bin", "/lib", "/opt"), // System libraries landlock.RWDirs( "/home/user/projects", // Source code "/home/user/.config", // Config files "/tmp", // Temporary files ), landlock.ConnectTCP(8000, 8080, 3000), // Development servers ) ``` -------------------------------- ### Apply All Restriction Types Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Combine filesystem, network, and other restriction types in a single `Restrict` call. Uses `.BestEffort()` for compatibility. ```go err := landlock.V8.BestEffort().Restrict( landlock.RODirs("/usr"), landlock.RWDirs("/tmp"), landlock.BindTCP(8080), landlock.ConnectTCP(53), ) ``` -------------------------------- ### Error Handling: Optional Paths Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Define rules, including optional paths that can be ignored if they don't exist, and apply them using `RestrictPaths`. ```go rules := []landlock.Rule{ landlock.RODirs("/usr"), landlock.RWDirs("/opt/optional").IgnoreIfMissing(), } err := landlock.V8.BestEffort().RestrictPaths(rules...) ``` -------------------------------- ### Configuration: Enable Logging for Subprocesses Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Configure Landlock to log audit events for child processes. Requires Landlock ABI V7 or higher. ```go cfg := landlock.V7.BestEffort(). EnableLoggingForSubprocesses() // Log child processes cfg.Restrict(rules...) ``` -------------------------------- ### NewConfig Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/INDEX.md Creates a new configuration with the provided arguments. It returns the configuration and an error if any occurs during creation. ```APIDOC ## NewConfig ### Description Creates a new configuration with the provided arguments. It returns the configuration and an error if any occurs during creation. ### Function Signature `NewConfig(args ...any) (*Config, error)` ### Returns - `*Config`: The newly created configuration object. - `error`: An error if the configuration could not be created. ``` -------------------------------- ### Combined Filesystem and Network Restrictions Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/architecture-and-patterns.md Apply both filesystem and network restrictions in a single call using V8 ABI and BestEffort mode. Includes read-only directories, read-write directories with ignore-if-missing, and specific TCP port bindings. ```go err := landlock.V8.BestEffort().Restrict( // Filesystem rules landlock.RODirs("/usr", "/bin"), landlock.RWDirs("/home/user/.config").IgnoreIfMissing(), // Network rules landlock.ConnectTCP(53), landlock.BindTCP(3000), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Handling Duplicate Access Rights in NewConfig Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/errors.md When multiple arguments of the same access right type are passed to NewConfig, an error occurs. Combine access rights using bitwise OR before passing them. ```go cfg, err := landlock.NewConfig( landlock.AccessFSSet(llsyscall.AccessFSReadFile), landlock.AccessFSSet(llsyscall.AccessFSExecute), // ERROR: duplicate ) ``` ```go cfg, err := landlock.NewConfig( landlock.AccessFSSet( llsyscall.AccessFSReadFile | llsyscall.AccessFSExecute, ), ) ``` -------------------------------- ### Config.String Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/INDEX.md Returns a string representation of the configuration. This is useful for debugging and logging. ```APIDOC ## Config.String ### Description Returns a string representation of the configuration. This is useful for debugging and logging. ### Method Signature `String() string ### Parameters None ### Returns - `string`: A string representation of the configuration. ``` -------------------------------- ### Graceful Degradation for Rule Compatibility Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/README.md Apply a rule with `BestEffort()` to ensure graceful degradation on older kernels. This allows the code to run even if the specific ABI version or feature is not supported. ```go // Gracefully degrade err := landlock.V2.BestEffort().RestrictPaths(rule) ``` -------------------------------- ### Fail Fast on Unsupported Kernel Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/errors.md This pattern demonstrates how to immediately stop execution if the Landlock kernel module is not supported, by checking the error returned from RestrictPaths. ```go err := landlock.V8.RestrictPaths( landlock.RODirs("/usr", "/bin"), ) if err != nil { log.Fatalf("Landlock not supported: %v", err) } ``` -------------------------------- ### Create Custom Path Access Rule Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/rules.md Use PathAccess to create a rule with a custom set of filesystem access rights. Ensure the accessFS parameter is a subset of the Config's restricted rights. Individual access rights are available as constants in `landlock/syscall`. ```go import ( "github.com/landlock-lsm/go-landlock/landlock" llsyscall "github.com/landlock-lsm/go-landlock/landlock/syscall" ) // Only allow reading files and executing, no directory access rule := landlock.PathAccess( llsyscall.AccessFSExecute | llsyscall.AccessFSReadFile, "/usr/bin", ) er := landlock.V8.BestEffort().RestrictPaths(rule) ``` -------------------------------- ### Restrict Paths with Rule Compatibility Check Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/README.md Apply a rule that requires a specific Landlock ABI version (V2). This will fail on older kernels unless `BestEffort()` is used. ```go // Fail on old kernels rule := landlock.RWDirs("/tmp").WithRefer() err := landlock.V2.RestrictPaths(rule) ``` -------------------------------- ### MustConfig Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/config-and-restrict.md Similar to `NewConfig`, but panics on error instead of returning an error. Use this when argument validity is certain. ```APIDOC ## MustConfig ```go func MustConfig(args ...any) Config ``` **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | args | ...any | Access right sets, same as `NewConfig`. | **Return type:** A new `Config` value. **Description:** Like `NewConfig`, but panics instead of returning an error. Use this only when you are certain that arguments are valid. **Panics:** Same conditions as `NewConfig` would error. **Usage example:** ```go cfg := landlock.MustConfig( landlock.AccessFSSet(llsyscall.AccessFSReadFile), ) ``` **Source location:** `landlock/config.go:208-215` ``` -------------------------------- ### Main Restriction Methods in Go-Landlock Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/README.md Overview of the primary methods for applying restrictions: RestrictPaths for filesystem, RestrictNet for network, RestrictScoped for IPC scopes, and a general Restrict for all types. ```go Config.RestrictPaths(rules ...FSRule) error // Restrict filesystem Config.RestrictNet(rules ...NetRule) error // Restrict network Config.RestrictScoped() error // Restrict IPC scopes Config.Restrict(rules ...Rule) error // Restrict all types ``` -------------------------------- ### Create Landlock Config with Panic Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/config-and-restrict.md Creates a new Landlock configuration, panicking on error instead of returning one. Use only when confident in the validity of the provided arguments. ```go cfg := landlock.MustConfig( landlock.AccessFSSet(llsyscall.AccessFSReadFile), ) ``` -------------------------------- ### BestEffort Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/config-and-restrict.md Returns a configuration that attempts to enforce the strongest possible rules, gracefully degrading to lower ABI versions or no enforcement if kernel features are unsupported. ```APIDOC ## BestEffort ```go func (c Config) BestEffort() Config ``` **Parameters:** None (receiver is `Config`). **Return type:** A new `Config` with best-effort mode enabled. **Description:** Returns a config that will opportunistically enforce the strongest rules possible, up to the given ABI version, gracefully degrading to lower ABI versions or no enforcement if the kernel does not support the requested features. A call to `RestrictPaths()` with a best-effort config will succeed even if Landlock is not available on the kernel at all, though no restrictions will be applied in that case. **Usage example:** ```go // Try V8, fall back to V7, V6, etc., or no Landlock if none available err := landlock.V8.BestEffort().RestrictPaths( landlock.RODirs("/usr", "/bin"), ) ``` **Source location:** `landlock/config.go:260-270` ``` -------------------------------- ### MustConfig Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/INDEX.md Creates a new configuration with the provided arguments. It panics if any error occurs during creation. ```APIDOC ## MustConfig ### Description Creates a new configuration with the provided arguments. It panics if any error occurs during creation. ### Function Signature `MustConfig(args ...any) Config ### Returns - `Config`: The newly created configuration object. ``` -------------------------------- ### FSRule.WithIoctlDev Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/rules.md Adds the "ioctl dev" access right to a filesystem rule, permitting the use of `ioctl(2)` on device files. This is an uncommon right and requires Landlock ABI V5 or later. ```APIDOC ## FSRule.WithIoctlDev ### Description Adds the "ioctl dev" access right to a filesystem rule, which permits using `ioctl(2)` on device files. This is an uncommon access right and is not included in `RWFiles` or `RWDirs` by default. ### Parameters None (receiver is `FSRule`). ### Return type A new `FSRule` with the "ioctl dev" access right added. ### Requires Landlock ABI V5 or later. ### Usage Example ```go import "github.com/landlock-lsm/go-landlock/landlock" rule := landlock.RWDirs("/dev").WithIoctlDev() err := landlock.V5.BestEffort().RestrictPaths(rule) ``` ``` -------------------------------- ### EnableLoggingForSubprocesses Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/config-and-restrict.md Enables audit logging of denied accesses that occur after an `execve(2)` call within the Landlock domain. This provides visibility into unauthorized access attempts by newly executed programs. Use this when all potential executables are expected to comply with restrictions. ```APIDOC ## EnableLoggingForSubprocesses ### Description Enables audit logging of denied accesses that occur after an `execve(2)` call within the Landlock domain. This provides visibility into unauthorized access attempts by newly executed programs. This flag should be used only when all potential executables within the domain are expected to comply with the access restrictions, since excessive audit log entries can make it harder to identify critical events. This method has no effect on kernels that do not support Landlock ABI V7 or later. When combined with `BestEffort()`, the flag is silently omitted on older kernels. ### Method `func (c Config) EnableLoggingForSubprocesses() Config` ### Parameters None (receiver is `Config`). ### Return type A new `Config` with the logging flag set. ### Requires Landlock ABI V7 or later (or use with `BestEffort()` for graceful degradation). ### Usage example: ```go cfg := landlock.V7.BestEffort(). EnableLoggingForSubprocesses(). RestrictPaths(landlock.RODirs("/usr")) ``` ``` -------------------------------- ### Create Custom Landlock Config Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/config-and-restrict.md Creates a new Landlock configuration with custom access rights, allowing specific restrictions instead of using a preset. Requires careful parameter validation. ```go import ( "log" "github.com/landlock-lsm/go-landlock/landlock" llsyscall "github.com/landlock-lsm/go-landlock/landlock/syscall" ) // Create a config that only restricts file execution cfg, err := landlock.NewConfig( landlock.AccessFSSet(llsyscall.AccessFSExecute), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Add 'Ioctl Dev' Access Right to Rule Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/rules.md Use WithIoctlDev to add the 'ioctl dev' access right, permitting the use of ioctl(2) on device files. This is an uncommon right and requires Landlock ABI V5 or later. ```go import "github.com/landlock-lsm/go-landlock/landlock" rule := landlock.RWDirs("/dev").WithIoctlDev() er := landlock.V5.BestEffort().RestrictPaths(rule) ``` -------------------------------- ### Filesystem Rule: Custom Access Rights Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Define a rule with specific access rights for a given path using `PathAccess`. ```go rule := landlock.PathAccess( llsyscall.AccessFSExecute | llsyscall.AccessFSReadFile, "/usr/bin", ) ``` -------------------------------- ### LandlockGetABIVersion Syscall Wrapper Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/syscall-constants.md Retrieves the Landlock ABI version supported by the kernel. Returns 0 if Landlock is not supported. Use this to check for Landlock compatibility. ```go func LandlockGetABIVersion() (version int, err error) ``` -------------------------------- ### Complete Lockdown with BestEffort Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md This snippet enforces a complete lockdown, denying all filesystem access. It's suitable for highly secure environments. ```go // Complete lockdown (no filesystem access) landlock.V8.BestEffort().Restrict() ``` -------------------------------- ### Create Read-Only File Rule Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/rules.md Creates a rule for read-only access to individual files, allowing reading and execution but not directory operations. Use this when only read access to specific files is needed. ```go import "github.com/landlock-lsm/go-landlock/landlock" err := landlock.V8.BestEffort().RestrictPaths( landlock.ROFiles("/etc/passwd", "/etc/hosts"), ) ``` -------------------------------- ### Create Read-Only Directory Rule Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/rules.md Creates a rule for read-only access to specified directories and files, allowing reading and execution. Use this to restrict modifications to filesystem contents. ```go import "github.com/landlock-lsm/go-landlock/landlock" err := landlock.V8.BestEffort().RestrictPaths( landlock.RODirs("/usr", "/bin"), ) ``` -------------------------------- ### Landlock ABI Version Presets Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Select the highest ABI version required for your restrictions. Use `.BestEffort()` for graceful degradation if a specific ABI is unavailable. ```go landlock.V1 // Basic filesystem (5.13+) landlock.V2 // + File reparenting (5.19+) landlock.V3 // + File truncation (6.2+) landlock.V4 // + Network operations (6.2+) landlock.V5 // + Device file IOCTL (6.3+) landlock.V6 // + IPC scopes (6.5+) landlock.V7 // + Audit logging (6.6+) landlock.V8 // + Thread sync (6.7+) ``` -------------------------------- ### Restrict Paths with Best Effort Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/config-and-restrict.md Applies restrictions using ABI V8, falling back gracefully on older kernels or if Landlock is unavailable. Ensures the call succeeds even if no restrictions are applied. ```go import "github.com/landlock-lsm/go-landlock/landlock" // Restrict using ABI V8, falling back gracefully on older kernels err := landlock.V8.BestEffort().RestrictPaths( landlock.RODirs("/usr", "/bin"), landlock.RWDirs("/tmp"), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Create Read-Write File Rule Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/rules.md Creates a rule for read and write access to individual files, excluding directory operations. This is suitable for scenarios requiring modification of specific files without affecting directories. ```go import "github.com/landlock-lsm/go-landlock/landlock" err := landlock.V8.BestEffort().RestrictPaths( landlock.RWFiles("/tmp/data.txt", "/var/log/myapp.log"), ) ``` -------------------------------- ### Config.EnableLoggingForSubprocesses Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/INDEX.md Enables logging for subprocesses. Returns the modified configuration. ```APIDOC ## Config.EnableLoggingForSubprocesses ### Description Enables logging for subprocesses. Returns the modified configuration. ### Method Signature `EnableLoggingForSubprocesses() Config ### Parameters None ### Returns - `Config`: The modified configuration object with logging enabled for subprocesses. ``` -------------------------------- ### Allow File Reparenting with WithRefer Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/README.md Enable file reparenting operations (renaming or linking files across directories) by using the `WithRefer()` method. This requires Landlock ABI V2 or later. ```go rule.WithRefer() // Requires ABI V2+ ``` -------------------------------- ### Filesystem Read-Only Files Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Specify files that should be accessible only for reading. ```go landlock.ROFiles("/etc/passwd") // Read-only files only ``` -------------------------------- ### Sandbox Web Server with Landlock Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Configure Landlock to sandbox a web server, allowing read-only access to web content and read-write access to log and temporary directories. It also binds TCP ports for web traffic. ```go // Sandbox for web server landlock.V8.BestEffort().Restrict( landlock.RODirs("/var/www"), landlock.RWDirs("/tmp", "/var/log"), landlock.BindTCP(80, 443), ) ``` -------------------------------- ### Optional Paths with IgnoreIfMissing Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/errors.md This pattern shows how to define rules for optional paths using IgnoreIfMissing(). It combines multiple rules, including those that might not exist, and applies them using BestEffort() for resilience. ```go rules := []landlock.Rule{ landlock.RODirs("/usr", "/bin"), landlock.RWDirs("/home/user/.config").IgnoreIfMissing(), landlock.RWDirs("/opt/myapp/data").IgnoreIfMissing(), } er := landlock.V8.BestEffort().RestrictPaths(rules...) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Handling Unknown Argument Type in NewConfig Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/errors.md An unsupported type passed to NewConfig will result in an error. Ensure only AccessFSSet, AccessNetSet, or ScopedSet values are provided. ```go cfg, err := landlock.NewConfig("invalid") // ERROR: not an AccessFSSet ``` -------------------------------- ### NewConfig Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/config-and-restrict.md Creates a new Landlock configuration with custom access rights, allowing precise specification of restricted operations. It accepts access right sets as arguments. ```APIDOC ## NewConfig ```go func NewConfig(args ...any) (*Config, error) ``` **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | args | ...any | Access right sets: `AccessFSSet`, `AccessNetSet`, or `ScopedSet`. Only one of each type may be provided. | **Return type:** Pointer to a new `Config` value, or an error if arguments are invalid or duplicated. **Description:** Creates a new Landlock configuration with custom access rights. This allows you to specify exactly which types of operations should be restricted, rather than using a preset configuration that restricts all operations at a given ABI level. **Errors:** - Error with message "only one AccessFSSet may be provided" if multiple `AccessFSSet` arguments are passed. - Error with message "only one AccessNetSet may be provided" if multiple `AccessNetSet` arguments are passed. - Error with message "only one ScopedSet may be provided" if multiple `ScopedSet` arguments are passed. - Error with message "unsupported AccessFSSet value; upgrade go-landlock?" if an invalid `AccessFSSet` is passed. - Error with message "unsupported AccessNetSet value; upgrade go-landlock?" if an invalid `AccessNetSet` is passed. - Error with message "unsupported ScopedSet value; upgrade go-landlock?" if an invalid `ScopedSet` is passed. - Error with message "unknown argument..." if an unsupported argument type is passed. **Usage example:** ```go import ( "log" "github.com/landlock-lsm/go-landlock/landlock" llsyscall "github.com/landlock-lsm/go-landlock/landlock/syscall" ) // Create a config that only restricts file execution cfg, err := landlock.NewConfig( landlock.AccessFSSet(llsyscall.AccessFSExecute), ) if err != nil { log.Fatal(err) } ``` **Source location:** `landlock/config.go:156-206` ``` -------------------------------- ### PathAccess Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/INDEX.md Creates a file system path access rule with specified access rights for the given paths. ```APIDOC ## PathAccess ### Description Creates a file system path access rule with specified access rights for the given paths. ### Function Signature `PathAccess(accessFS AccessFSSet, paths ...string) FSRule ### Parameters - `accessFS` (AccessFSSet): The set of file system access rights to grant. - `paths` (...string): A variadic list of file system paths to apply the access rule to. ### Returns - `FSRule`: An FSRule object representing the specified path access. ``` -------------------------------- ### Graceful Degradation with BestEffort Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/errors.md Utilizes BestEffort() for graceful degradation, ensuring the program continues to run even if Landlock features are unavailable. Errors are unexpected in this pattern. ```go err := landlock.V8.BestEffort().RestrictPaths( landlock.RODirs("/usr", "/bin"), ) if err != nil { // Should never happen with BestEffort, but handle just in case log.Fatalf("Unexpected error: %v", err) } ``` -------------------------------- ### Update go-landlock Library Source: https://github.com/landlock-lsm/go-landlock/blob/main/docs/upgrade.md Use this command to update the go-landlock library to the latest version. ```bash go get -u github.com/landlock-lsm/go-landlock ``` -------------------------------- ### Fine-Grained File Read Permissions Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/README.md Apply fine-grained permissions to only allow reading specific file types from a given directory. Requires importing the syscall package. ```go import llsyscall "github.com/landlock-lsm/go-landlock/landlock/syscall" // Only allow reading specific file types rule := landlock.PathAccess( llsyscall.AccessFSReadFile | llsyscall.AccessFSReadDir, "/etc/config", ) err := landlock.V8.BestEffort().RestrictPaths(rule) ``` -------------------------------- ### Best Effort Config Mode Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/config-and-restrict.md Returns a config that opportunistically enforces the strongest rules possible, gracefully degrading to lower ABI versions or no enforcement if kernel features are unsupported. Calls to RestrictPaths() will succeed even if Landlock is unavailable. ```go // Try V8, fall back to V7, V6, etc., or no Landlock if none available err := landlock.V8.BestEffort().RestrictPaths( landlock.RODirs("/usr", "/bin"), ) ``` -------------------------------- ### Filesystem Rules in Go-Landlock Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/README.md Defines various filesystem rules including read-only and read-write access to directories and files, and custom path access rights. Supports modifiers like WithRefer, WithIoctlDev, and IgnoreIfMissing. ```go RODirs(paths...) // Read-only access to directories RWDirs(paths...) // Read-write access to directories ROFiles(paths...) // Read-only access to files only RWFiles(paths...) // Read-write access to files only PathAccess(rights, paths...) // Custom access rights ``` ```go rule.WithRefer() // Add file reparenting right (V2+) rule.WithIoctlDev() // Add device file IOCTL right (V5+) rule.IgnoreIfMissing() // Ignore missing paths instead of erroring ``` -------------------------------- ### Error Handling: Fail if Landlock Unavailable Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Enforce the availability of a specific Landlock ABI version. The program exits if the required version is not supported. ```go err := landlock.V4.RestrictPaths( landlock.RODirs("/usr"), ) if err != nil { log.Fatal("Landlock V4 required") } ``` -------------------------------- ### Go: Create a Network Rule to Bind to a TCP Port Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/rules.md Use BindTCP to create a network rule that allows binding to a specific TCP port. This is typically used with `net.Listen` and requires Landlock ABI V4 or later. Note that this restriction does not apply to Multipath TCP (MPTCP) sockets. ```go import "github.com/landlock-lsm/go-landlock/landlock" err := landlock.V4.BestEffort().RestrictNet( landlock.BindTCP(8080), ) ``` -------------------------------- ### RWFiles Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/api-reference/rules.md Creates a rule that grants read and write access to files under the specified paths, including reading and writing file contents and executing files, but does not permit access to directories. It notably excludes the right to use IOCTL on device files without additional options. ```APIDOC ## RWFiles ### Description Creates a rule that grants read and write access to files under the given paths, but does not permit access to directories. It includes reading and writing file contents and executing files. Directory operations are not permitted. Notable exclusions include not granting the right to use IOCTL on device files (use `FSRule.WithIoctlDev()` to add this right). ### Method `RWFiles` ### Parameters #### Path Parameters - **paths** (...string) - Required - One or more file paths to grant read-write access to. ### Return type `FSRule` — a filesystem rule. ### Usage example: ```go import "github.com/landlock-lsm/go-landlock/landlock" err := landlock.V8.BestEffort().RestrictPaths( landlock.RWFiles("/tmp/data.txt", "/var/log/myapp.log"), ) ``` ``` -------------------------------- ### Apply Network Restrictions Source: https://github.com/landlock-lsm/go-landlock/blob/main/_autodocs/QUICK-REFERENCE.md Apply network-related rules, such as allowed TCP ports, using a specific Landlock ABI version. Uses `.BestEffort()` for compatibility. ```go err := landlock.V4.BestEffort().RestrictNet( landlock.BindTCP(3000), landlock.ConnectTCP(443), ) ```