| 1 | // Package restrict can be used to restrict further file system access of the |
| 2 | // process if the operating system provides an API for that. |
| 3 | package restrict |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "log" |
| 8 | "os" |
| 9 | |
| 10 | "github.com/landlock-lsm/go-landlock/landlock" |
| 11 | ) |
| 12 | |
| 13 | // ExtraHook is set when testing to make the landlock rule set more permissive. |
| 14 | var ExtraHook func() []landlock.Rule |
| 15 | |
| 16 | func MaybeFileSystem(roDirsOrFiles []string, rwDirs []string) error { |
| 17 | re := ExtraHook |
| 18 | if re == nil { |
| 19 | re = func() []landlock.Rule { |
| 20 | return nil |
| 21 | } |
| 22 | } |
| 23 | var roDirs, roFiles []string |
| 24 | for _, fn := range roDirsOrFiles { |
| 25 | st, err := os.Stat(fn) |
| 26 | if err != nil { |
| 27 | return err |
| 28 | } |
| 29 | if st.IsDir() { |
| 30 | roDirs = append(roDirs, fn) |
| 31 | } else { |
| 32 | roFiles = append(roFiles, fn) |
| 33 | } |
| 34 | } |
| 35 | log.Printf("setting up landlock ACL (paths ro: %q, paths rw: %q)", roDirs, rwDirs) |
| 36 | err := landlock.V3.BestEffort().RestrictPaths( |
| 37 | append(re(), []landlock.Rule{ |
| 38 | landlock.RODirs(defaultRoDirs...).IgnoreIfMissing(), |
| 39 | landlock.RODirs(roDirs...).IgnoreIfMissing(), |
| 40 | landlock.ROFiles(roFiles...).IgnoreIfMissing(), |
| 41 | landlock.RWDirs(rwDirs...).WithRefer(), |
| 42 | }...)...) |
| 43 | if err != nil { |
| 44 | return fmt.Errorf("landlock: %v", err) |
| 45 | } |
| 46 | |
| 47 | // Check whether landlock worked and print the result to the log. |
| 48 | // |
| 49 | // We use /sys because that path should never be required |
| 50 | // for regular functioning, yet is standard enough to be present |
| 51 | // on all supported Linux versions (including gokrazy). |
| 52 | const verifyPath = "/sys" |
| 53 | _, err = os.ReadDir(verifyPath) |
| 54 | if err == nil { |
| 55 | log.Printf("landlock seems ineffective: readdir(%s) unexpectedly worked!", verifyPath) |
| 56 | } else { |
| 57 | log.Printf("landlock verified: readdir(%s) = %v", verifyPath, err) |
| 58 | } |
| 59 | |
| 60 | return nil |
| 61 | } |