aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/app/spcontainer.go
blob: 62fffc8ad87e08d68829f7f23cef88ed2faf205b (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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package app

import (
	"encoding/gob"
	"errors"
	"io/fs"
	"os"
	"path"
	"strconv"
	"syscall"

	"hakurei.app/container"
	"hakurei.app/container/bits"
	"hakurei.app/container/check"
	"hakurei.app/container/fhs"
	"hakurei.app/container/seccomp"
	"hakurei.app/hst"
	"hakurei.app/message"
	"hakurei.app/system/dbus"
)

const varRunNscd = fhs.Var + "run/nscd"

func init() { gob.Register(new(spParamsOp)) }

// spParamsOp initialises unordered fields of [container.Params] and the optional root filesystem.
// This outcomeOp is hardcoded to always run first.
type spParamsOp struct {
	// Value of $TERM, stored during toSystem.
	Term string
	// Whether $TERM is set, stored during toSystem.
	TermSet bool
}

func (s *spParamsOp) toSystem(state *outcomeStateSys) error {
	s.Term, s.TermSet = state.k.lookupEnv("TERM")
	state.sys.Ensure(state.sc.SharePath, 0711)
	return nil
}

func (s *spParamsOp) toContainer(state *outcomeStateParams) error {
	// pass $TERM for proper terminal I/O in initial process
	if s.TermSet {
		state.env["TERM"] = s.Term
	}

	// in practice there should be less than 30 system mount points
	const preallocateOpsCount = 1 << 5

	state.params.Hostname = state.Container.Hostname
	state.params.RetainSession = state.Container.Tty
	state.params.HostNet = state.Container.HostNet
	state.params.HostAbstract = state.Container.HostAbstract

	if state.Container.Path == nil {
		return newWithMessage("invalid program path")
	}
	state.params.Path = state.Container.Path

	if len(state.Container.Args) == 0 {
		state.params.Args = []string{state.Container.Path.String()}
	} else {
		state.params.Args = state.Container.Args
	}

	// the container is canceled when shim is requested to exit or receives an interrupt or termination signal;
	// this behaviour is implemented in the shim
	state.params.ForwardCancel = state.Shim.WaitDelay > 0

	if state.Container.Multiarch {
		state.params.SeccompFlags |= seccomp.AllowMultiarch
	}

	if !state.Container.SeccompCompat {
		state.params.SeccompPresets |= bits.PresetExt
	}
	if !state.Container.Devel {
		state.params.SeccompPresets |= bits.PresetDenyDevel
	}
	if !state.Container.Userns {
		state.params.SeccompPresets |= bits.PresetDenyNS
	}
	if !state.Container.Tty {
		state.params.SeccompPresets |= bits.PresetDenyTTY
	}

	if state.Container.MapRealUID {
		state.params.Uid = state.Mapuid
		state.params.Gid = state.Mapgid
	}

	{
		state.as.AutoEtcPrefix = state.id.String()
		ops := make(container.Ops, 0, preallocateOpsCount+len(state.Container.Filesystem))
		state.params.Ops = &ops
		state.as.Ops = opsAdapter{&ops}
	}

	rootfs, filesystem, _ := resolveRoot(state.Container)
	state.filesystem = filesystem
	if rootfs != nil {
		rootfs.Apply(&state.as)
	}

	// early mount points
	state.params.
		Proc(fhs.AbsProc).
		Tmpfs(hst.AbsTmp, 1<<12, 0755)
	if !state.Container.Device {
		state.params.DevWritable(fhs.AbsDev, true)
	} else {
		state.params.Bind(fhs.AbsDev, fhs.AbsDev, bits.BindWritable|bits.BindDevice)
	}
	// /dev is mounted readonly later on, this prevents /dev/shm from going readonly with it
	state.params.Tmpfs(fhs.AbsDev.Append("shm"), 0, 01777)

	return nil
}

func init() { gob.Register(new(spFilesystemOp)) }

// spFilesystemOp applies configured filesystems to [container.Params], excluding the optional root filesystem.
type spFilesystemOp struct {
	// Matched paths to cover. Stored during toSystem.
	HidePaths []*check.Absolute
}

func (s *spFilesystemOp) toSystem(state *outcomeStateSys) error {
	/* 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 */
	hidePaths := []string{
		state.sc.RuntimePath.String(),
		state.sc.SharePath.String(),

		// this causes emulated passwd database to be bypassed on some /etc/ setups
		varRunNscd,
	}

	_, systemBusAddr := dbus.Address()
	if entries, err := dbus.Parse([]byte(systemBusAddr)); err != nil {
		return &hst.AppError{Step: "parse dbus address", Err: 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 == fhs.Root {
							state.msg.Verbosef("dbus socket %q is in an unusual location", pair[1])
						}
						hidePaths = append(hidePaths, dir)
					} else {
						state.msg.Verbosef("dbus socket %q is not absolute", pair[1])
					}
				}
			}
		}
	}
	hidePathMatch := make([]bool, len(hidePaths))
	for i := range hidePaths {
		if err := evalSymlinks(state.msg, state.k, &hidePaths[i]); err != nil {
			return &hst.AppError{Step: "evaluate path hiding target", Err: err}
		}
	}

	_, filesystem, autoroot := resolveRoot(state.Container)

	var hidePathSourceCount int
	for i, c := range filesystem {
		if !c.Valid() {
			return newWithMessage("invalid filesystem at index " + strconv.Itoa(i))
		}

		// fs counter
		hidePathSourceCount += len(c.Host())
	}

	// AutoRootOp is a collection of many BindMountOp internally
	var autoRootEntries []fs.DirEntry
	if autoroot != nil {
		if d, err := state.k.readdir(autoroot.Source.String()); err != nil {
			return &hst.AppError{Step: "access autoroot source", Err: err}
		} else {
			// autoroot counter
			hidePathSourceCount += len(d)
			autoRootEntries = d
		}
	}

	hidePathSource := make([]*check.Absolute, 0, hidePathSourceCount)

	// fs append
	for _, c := range filesystem {
		// all entries already checked above
		hidePathSource = append(hidePathSource, c.Host()...)
	}

	// autoroot append
	if autoroot != nil {
		for _, ent := range autoRootEntries {
			name := ent.Name()
			if container.IsAutoRootBindable(state.msg, name) {
				hidePathSource = append(hidePathSource, autoroot.Source.Append(name))
			}
		}
	}

	// evaluated path, input path
	hidePathSourceEval := make([][2]string, len(hidePathSource))
	for i, a := range hidePathSource {
		if a == nil {
			// unreachable
			return newWithMessage("impossible path hiding state reached")
		}

		hidePathSourceEval[i] = [2]string{a.String(), a.String()}
		if err := evalSymlinks(state.msg, state.k, &hidePathSourceEval[i][0]); err != nil {
			return &hst.AppError{Step: "evaluate path hiding source", Err: err}
		}
	}

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

			if ok, err := deepContainsH(p[0], hidePaths[i]); err != nil {
				return &hst.AppError{Step: "determine path hiding outcome", Err: err}
			} else if ok {
				hidePathMatch[i] = true
				state.msg.Verbosef("hiding path %q from %q", hidePaths[i], p[1])
			}
		}
	}

	// copy matched paths for shim
	for i, ok := range hidePathMatch {
		if ok {
			if a, err := check.NewAbs(hidePaths[i]); err != nil {
				var absoluteError *check.AbsoluteError
				if !errors.As(err, &absoluteError) {
					return newWithMessageError(absoluteError.Error(), absoluteError)
				}
				if absoluteError == nil {
					return newWithMessage("impossible path checking state reached")
				}
				return newWithMessage("invalid path hiding candidate " + strconv.Quote(absoluteError.Pathname))
			} else {
				s.HidePaths = append(s.HidePaths, a)
			}
		}
	}

	return nil
}

func (s *spFilesystemOp) toContainer(state *outcomeStateParams) error {
	for i, c := range state.filesystem {
		if !c.Valid() {
			return newWithMessage("invalid filesystem at index " + strconv.Itoa(i))
		}
		c.Apply(&state.as)
	}

	for _, a := range s.HidePaths {
		state.params.Tmpfs(a, 1<<13, 0755)
	}

	// no more configured paths beyond this point
	if !state.Container.Device {
		state.params.Remount(fhs.AbsDev, syscall.MS_RDONLY)
	}
	return nil
}

// resolveRoot handles the root filesystem special case for [hst.FilesystemConfig] and additionally resolves autoroot
// as it requires special handling during path hiding.
func resolveRoot(c *hst.ContainerConfig) (rootfs hst.FilesystemConfig, filesystem []hst.FilesystemConfigJSON, autoroot *hst.FSBind) {
	// root filesystem special case
	filesystem = c.Filesystem
	// valid happens late, so root gets it here
	if len(filesystem) > 0 && filesystem[0].Valid() && filesystem[0].Path().String() == fhs.Root {
		// if the first element targets /, it is inserted early and excluded from path hiding
		rootfs = filesystem[0].FilesystemConfig
		filesystem = filesystem[1:]

		// autoroot requires special handling during path hiding
		if b, ok := rootfs.(*hst.FSBind); ok && b.IsAutoRoot() {
			autoroot = b
		}
	}
	return
}

// evalSymlinks calls syscallDispatcher.evalSymlinks but discards errors unwrapping to [fs.ErrNotExist].
func evalSymlinks(msg message.Msg, k syscallDispatcher, v *string) error {
	if p, err := k.evalSymlinks(*v); err != nil {
		if !errors.Is(err, fs.ErrNotExist) {
			return err
		}
		msg.Verbosef("path %q does not yet exist", *v)
	} else {
		*v = p
	}
	return nil
}

// opsAdapter implements [hst.Ops] on [container.Ops].
type opsAdapter struct{ *container.Ops }

func (p opsAdapter) Tmpfs(target *check.Absolute, size int, perm os.FileMode) hst.Ops {
	return opsAdapter{p.Ops.Tmpfs(target, size, perm)}
}

func (p opsAdapter) Readonly(target *check.Absolute, perm os.FileMode) hst.Ops {
	return opsAdapter{p.Ops.Readonly(target, perm)}
}

func (p opsAdapter) Bind(source, target *check.Absolute, flags int) hst.Ops {
	return opsAdapter{p.Ops.Bind(source, target, flags)}
}

func (p opsAdapter) Overlay(target, state, work *check.Absolute, layers ...*check.Absolute) hst.Ops {
	return opsAdapter{p.Ops.Overlay(target, state, work, layers...)}
}

func (p opsAdapter) OverlayReadonly(target *check.Absolute, layers ...*check.Absolute) hst.Ops {
	return opsAdapter{p.Ops.OverlayReadonly(target, layers...)}
}

func (p opsAdapter) Link(target *check.Absolute, linkName string, dereference bool) hst.Ops {
	return opsAdapter{p.Ops.Link(target, linkName, dereference)}
}

func (p opsAdapter) Root(host *check.Absolute, flags int) hst.Ops {
	return opsAdapter{p.Ops.Root(host, flags)}
}

func (p opsAdapter) Etc(host *check.Absolute, prefix string) hst.Ops {
	return opsAdapter{p.Ops.Etc(host, prefix)}
}