aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/app/container_linux.go
blob: cd9448a8e7bce2bb8d6aac1f7f9266d479ca2a2f (plain)
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package app

import (
	"errors"
	"fmt"
	"io/fs"
	"maps"
	"path"
	"slices"
	"syscall"

	"hakurei.app/container"
	"hakurei.app/container/seccomp"
	"hakurei.app/hst"
	"hakurei.app/internal/sys"
	"hakurei.app/system/dbus"
)

// in practice there should be less than 30 entries added by the runtime;
// allocating slightly more as a margin for future expansion
const preallocateOpsCount = 1 << 5

// newContainer initialises [container.Params] via [hst.ContainerConfig].
// Note that remaining container setup must be queued by the caller.
func newContainer(s *hst.ContainerConfig, os sys.State, prefix string, uid, gid *int) (*container.Params, map[string]string, error) {
	if s == nil {
		return nil, nil, syscall.EBADE
	}

	params := &container.Params{
		Hostname:       s.Hostname,
		SeccompFlags:   s.SeccompFlags,
		SeccompPresets: s.SeccompPresets,
		RetainSession:  s.Tty,
		HostNet:        s.Net,

		// the container is canceled when shim is requested to exit or receives an interrupt or termination signal;
		// this behaviour is implemented in the shim
		ForwardCancel: s.WaitDelay >= 0,
	}

	{
		ops := make(container.Ops, 0, preallocateOpsCount+len(s.Filesystem)+len(s.Link)+len(s.Cover))
		params.Ops = &ops
	}

	if s.Multiarch {
		params.SeccompFlags |= seccomp.AllowMultiarch
	}

	if !s.SeccompCompat {
		params.SeccompPresets |= seccomp.PresetExt
	}
	if !s.Devel {
		params.SeccompPresets |= seccomp.PresetDenyDevel
	}
	if !s.Userns {
		params.SeccompPresets |= seccomp.PresetDenyNS
	}
	if !s.Tty {
		params.SeccompPresets |= seccomp.PresetDenyTTY
	}

	if s.MapRealUID {
		/* some programs fail to connect to dbus session running as a different uid
		so this workaround is introduced to map priv-side caller uid in container */
		params.Uid = os.Getuid()
		*uid = params.Uid
		params.Gid = os.Getgid()
		*gid = params.Gid
	} else {
		*uid = container.OverflowUid()
		*gid = container.OverflowGid()
	}

	if s.AutoRoot != "" {
		if !path.IsAbs(s.AutoRoot) {
			return nil, nil, fmt.Errorf("auto root target %q not absolute", s.AutoRoot)
		}
		params.Root(s.AutoRoot, prefix, s.RootFlags)
	}

	params.
		Proc("/proc").
		Tmpfs(hst.Tmp, 1<<12, 0755)

	if !s.Device {
		params.Dev("/dev").Mqueue("/dev/mqueue")
	} else {
		params.Bind("/dev", "/dev", container.BindWritable|container.BindDevice)
	}

	/* retrieve paths and hide them if they're made available in the sandbox;
	this feature tries to improve user experience of permissive defaults, and
	to warn about issues in custom configuration; it is NOT a security feature
	and should not be treated as such, ALWAYS be careful with what you bind */
	var hidePaths []string
	sc := os.Paths()
	hidePaths = append(hidePaths, sc.RuntimePath, sc.SharePath)
	_, systemBusAddr := dbus.Address()
	if entries, err := dbus.Parse([]byte(systemBusAddr)); err != nil {
		return nil, nil, err
	} else {
		// there is usually only one, do not preallocate
		for _, entry := range entries {
			if entry.Method != "unix" {
				continue
			}
			for _, pair := range entry.Values {
				if pair[0] == "path" {
					if path.IsAbs(pair[1]) {
						// get parent dir of socket
						dir := path.Dir(pair[1])
						if dir == "." || dir == "/" {
							os.Printf("dbus socket %q is in an unusual location", pair[1])
						}
						hidePaths = append(hidePaths, dir)
					} else {
						os.Printf("dbus socket %q is not absolute", pair[1])
					}
				}
			}
		}
	}
	hidePathMatch := make([]bool, len(hidePaths))
	for i := range hidePaths {
		if err := evalSymlinks(os, &hidePaths[i]); err != nil {
			return nil, nil, err
		}
	}
	// evaluated path, input path
	hidePathSource := make([][2]string, 0, len(s.Filesystem))

	// AutoRoot is a collection of many BindMountOp internally
	if s.AutoRoot != "" {
		if d, err := os.ReadDir(s.AutoRoot); err != nil {
			return nil, nil, err
		} else {
			hidePathSource = slices.Grow(hidePathSource, len(d))
			for _, ent := range d {
				name := ent.Name()
				if container.IsAutoRootBindable(name) {
					name = path.Join(s.AutoRoot, name)
					srcP := [2]string{name, name}
					if err = evalSymlinks(os, &srcP[0]); err != nil {
						return nil, nil, err
					}
					hidePathSource = append(hidePathSource, srcP)
				}
			}
		}
	}

	for _, c := range s.Filesystem {
		if c == nil {
			continue
		}

		if !path.IsAbs(c.Src) {
			return nil, nil, fmt.Errorf("src path %q is not absolute", c.Src)
		}

		dest := c.Dst
		if c.Dst == "" {
			dest = c.Src
		} else if !path.IsAbs(dest) {
			return nil, nil, fmt.Errorf("dst path %q is not absolute", dest)
		}

		p := [2]string{c.Src, c.Src}
		if err := evalSymlinks(os, &p[0]); err != nil {
			return nil, nil, err
		}
		hidePathSource = append(hidePathSource, p)

		var flags int
		if c.Write {
			flags |= container.BindWritable
		}
		if c.Device {
			flags |= container.BindDevice | container.BindWritable
		}
		if !c.Must {
			flags |= container.BindOptional
		}
		params.Bind(c.Src, dest, flags)
	}

	for _, p := range hidePathSource {
		for i := range hidePaths {
			// skip matched entries
			if hidePathMatch[i] {
				continue
			}

			if ok, err := deepContainsH(p[0], hidePaths[i]); err != nil {
				return nil, nil, err
			} else if ok {
				hidePathMatch[i] = true
				os.Printf("hiding path %q from %q", hidePaths[i], p[1])
			}
		}
	}

	// cover matched paths
	for i, ok := range hidePathMatch {
		if ok {
			params.Tmpfs(hidePaths[i], 1<<13, 0755)
		}
	}

	for _, l := range s.Link {
		params.Link(l[0], l[1])
	}

	if !s.AutoEtc {
		if s.Etc != "" {
			params.Bind(s.Etc, "/etc", 0)
		}
	} else {
		etcPath := s.Etc
		if etcPath == "" {
			etcPath = "/etc"
		}
		params.Etc(etcPath, prefix)
	}

	return params, maps.Clone(s.Env), nil
}

func evalSymlinks(os sys.State, v *string) error {
	if p, err := os.EvalSymlinks(*v); err != nil {
		if !errors.Is(err, fs.ErrNotExist) {
			return err
		}
		os.Printf("path %q does not yet exist", *v)
	} else {
		*v = p
	}
	return nil
}