aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/sandbox/mount.go
blob: eaede7b4b2db0bf1c5124af8c9fe1dca1946f81f (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
package sandbox

import (
	"errors"
	"fmt"
	"os"
	"strings"
	"syscall"

	"git.gensokyo.uk/security/fortify/internal/fmsg"
)

const (
	BindOptional = 1 << iota
	BindSource
	BindRecursive
	BindWritable
	BindDevices
)

func bindMount(src, dest string, flags int) error {
	target := toSysroot(dest)
	var source string

	if flags&BindSource == 0 {
		// this is what bwrap does, so the behaviour is kept for now,
		// however recursively resolving links might improve user experience
		if rp, err := realpathHost(src); err != nil {
			if os.IsNotExist(err) {
				if flags&BindOptional != 0 {
					return nil
				} else {
					return fmsg.WrapError(err,
						fmt.Sprintf("path %q does not exist", src))
				}
			}
			return fmsg.WrapError(err, err.Error())
		} else {
			source = toHost(rp)
		}
	} else if flags&BindOptional != 0 {
		return fmsg.WrapError(syscall.EINVAL,
			"flag source excludes optional")
	} else {
		source = toHost(src)
	}

	if fi, err := os.Stat(source); err != nil {
		return fmsg.WrapError(err, err.Error())
	} else if fi.IsDir() {
		if err = os.MkdirAll(target, 0755); err != nil {
			return fmsg.WrapErrorSuffix(err,
				fmt.Sprintf("cannot create directory %q:", dest))
		}
	} else if err = ensureFile(target, 0444); err != nil {
		if errors.Is(err, syscall.EISDIR) {
			return fmsg.WrapError(err,
				fmt.Sprintf("path %q is a directory", dest))
		}
		return fmsg.WrapErrorSuffix(err,
			fmt.Sprintf("cannot create %q:", dest))
	}

	var mf uintptr = syscall.MS_SILENT | syscall.MS_BIND
	if flags&BindRecursive != 0 {
		mf |= syscall.MS_REC
	}
	if flags&BindWritable == 0 {
		mf |= syscall.MS_RDONLY
	}
	if flags&BindDevices == 0 {
		mf |= syscall.MS_NODEV
	}
	if fmsg.Load() {
		if strings.TrimPrefix(source, hostPath) == strings.TrimPrefix(target, sysrootPath) {
			fmsg.Verbosef("resolved %q flags %#x", target, mf)
		} else {
			fmsg.Verbosef("resolved %q on %q flags %#x", source, target, mf)
		}
	}
	return fmsg.WrapErrorSuffix(syscall.Mount(source, target, "", mf, ""),
		fmt.Sprintf("cannot bind %q on %q:", src, dest))
}

func mountTmpfs(fsname, name string, size int, perm os.FileMode) error {
	target := toSysroot(name)
	if err := os.MkdirAll(target, perm); err != nil {
		return err
	}
	opt := fmt.Sprintf("mode=%#o", perm)
	if size > 0 {
		opt += fmt.Sprintf(",size=%d", size)
	}
	return fmsg.WrapErrorSuffix(syscall.Mount(fsname, target, "tmpfs",
		syscall.MS_NOSUID|syscall.MS_NODEV, opt),
		fmt.Sprintf("cannot mount tmpfs on %q:", name))
}