| 1 |
//go:build linux |
| 2 |
|
| 3 |
package landlock |
| 4 |
|
| 5 |
import ( |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"syscall" |
| 9 |
|
| 10 |
ll "github.com/landlock-lsm/go-landlock/landlock/syscall" |
| 11 |
"golang.org/x/sys/unix" |
| 12 |
) |
| 13 |
|
| 14 |
func (r FSRule) addToRuleset(rulesetFD int, c Config) error { |
| 15 |
effectiveAccessFS := r.accessFS |
| 16 |
if !r.enforceSubset { |
| 17 |
effectiveAccessFS = effectiveAccessFS.intersect(c.handledAccessFS) |
| 18 |
} |
| 19 |
if effectiveAccessFS == 0 { |
| 20 |
// Adding this to the ruleset would be a no-op |
| 21 |
// and result in an error. |
| 22 |
return nil |
| 23 |
} |
| 24 |
for _, path := range r.paths { |
| 25 |
if err := addPath(rulesetFD, path, effectiveAccessFS); err != nil { |
| 26 |
if r.ignoreMissing && errors.Is(err, unix.ENOENT) { |
| 27 |
continue // Skip this path. |
| 28 |
} |
| 29 |
return fmt.Errorf("populating ruleset for %q with access %v: %w", path, effectiveAccessFS, err) |
| 30 |
} |
| 31 |
} |
| 32 |
return nil |
| 33 |
} |
| 34 |
|
| 35 |
func addPath(rulesetFd int, path string, access AccessFSSet) error { |
| 36 |
fd, err := syscall.Open(path, unix.O_PATH|unix.O_CLOEXEC, 0) |
| 37 |
if err != nil { |
| 38 |
return fmt.Errorf("open: %w", err) |
| 39 |
} |
| 40 |
defer syscall.Close(fd) |
| 41 |
|
| 42 |
pathBeneath := ll.PathBeneathAttr{ |
| 43 |
ParentFd: fd, |
| 44 |
AllowedAccess: uint64(access), |
| 45 |
} |
| 46 |
err = ll.LandlockAddPathBeneathRule(rulesetFd, &pathBeneath, 0) |
| 47 |
if err != nil { |
| 48 |
if errors.Is(err, syscall.EINVAL) { |
| 49 |
// The ruleset access permissions must be a superset of the ones we restrict to. |
| 50 |
// This should never happen because the call to addPath() ensures that. |
| 51 |
err = fmt.Errorf("inconsistent access rights (using directory access rights on a regular file?): %w", err) |
| 52 |
} else if errors.Is(err, syscall.ENOMSG) && access == 0 { |
| 53 |
err = fmt.Errorf("empty access rights: %w", err) |
| 54 |
} else { |
| 55 |
// Other errors should never happen. |
| 56 |
err = bug(err) |
| 57 |
} |
| 58 |
return fmt.Errorf("landlock_add_rule: %w", err) |
| 59 |
} |
| 60 |
return nil |
| 61 |
} |