-
Notifications
You must be signed in to change notification settings - Fork 1
/
landlock_linux.go
109 lines (91 loc) · 1.95 KB
/
landlock_linux.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Copyright (c) Seth Hoenig
// SPDX-License-Identifier: MPL-2.0
//go:build linux
package landlock
import (
"errors"
"fmt"
"syscall"
"github.com/hashicorp/go-set/v2"
"golang.org/x/sys/unix"
)
var (
ErrLandlockNotAvailable = errors.New("landlock not available")
ErrLandlockFailedToLock = errors.New("landlock failed to lock")
)
type locker struct {
paths *set.HashSet[*Path, string]
}
// New creates a Locker that allows the given paths and permissions.
func New(paths ...*Path) Locker {
s := set.NewHashSet[*Path](10)
for _, path := range paths {
switch path.mode {
case modeShared:
s.InsertSlice(shared)
case modeStdio:
s.InsertSlice(stdio)
case modeTTY:
s.InsertSlice(tty)
case modeTmp:
s.InsertSlice(tmp)
case modeVMInfo:
s.InsertSlice(vminfo)
case modeDNS:
s.InsertSlice(dns)
case modeCerts:
s.InsertSlice(certs)
default:
s.Insert(path)
}
}
return &locker{paths: s}
}
func (l *locker) Lock(s Safety) error {
if !available {
if s == Try || s == OnlyAvailable {
return nil
}
return ErrLandlockNotAvailable
}
if err := l.lock(); err != nil && s != Try {
return errors.Join(ErrLandlockFailedToLock, err)
}
return nil
}
func (l *locker) String() string {
return l.paths.StringFunc(func(p *Path) string {
return fmt.Sprintf("%s:%s", p.mode, p.path)
})
}
func (l *locker) lock() error {
c := capabilities()
ra := rulesetAttr{handleAccessFS: uint64(c)}
fd, err := ruleset(&ra)
if err != nil {
return err
}
list := l.paths.Slice()
for _, path := range list {
if err = l.lockOne(path, fd); err != nil {
return err
}
}
if err = prctl(); err != nil {
return err
}
if err = restrict(fd); err != nil {
return err
}
return nil
}
func (l *locker) lockOne(p *Path, fd int) error {
allow := p.access()
ba := beneathAttr{allowedAccess: uint64(allow)}
fd2, err := syscall.Open(p.path, unix.O_PATH|unix.O_CLOEXEC, 0)
if err != nil {
return err
}
ba.parentFd = fd2
return add(fd, &ba)
}