Debian Codegraph @

internal/maincmd/namespacing_linux.go

raw symbols SCIP
1 //go:build linux && !nonamespacing
2
3 package maincmd
4
5 import (
6 "errors"
7 "fmt"
8 "net"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strconv"
13 "syscall"
14
15 "github.com/gokrazy/rsync/internal/rsyncos"
16 "github.com/gokrazy/rsync/rsyncd"
17 "golang.org/x/sys/unix"
18 )
19
20 // based on https://medium.com/@teddyking/namespaces-in-go-mount-e4c04fe9fb29
21 func pivotRoot(newroot string) error {
22 putold := filepath.Join(newroot, "/.pivot_root")
23
24 // create putold directory
25 if err := os.MkdirAll(putold, 0700); err != nil {
26 return err
27 }
28
29 // bind mount newroot to itself - this is a slight hack
30 // needed to work around a pivot_root requirement
31 err := syscall.Mount(
32 newroot,
33 newroot,
34 "",
35 syscall.MS_BIND|syscall.MS_REC,
36 "")
37 if err != nil {
38 return fmt.Errorf("mount(): %v", err)
39 }
40
41 // remount root as read-only: https://unix.stackexchange.com/questions/128336/why-doesnt-mount-respect-the-read-only-option-for-bind-mounts
42 err = syscall.Mount(
43 newroot,
44 newroot,
45 "",
46 syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY,
47 "")
48 if err != nil {
49 return fmt.Errorf("mount -o remount,ro: %v", err)
50 }
51
52 // TODO: when trying to use syscall.PivotRoot(".", ".") as described in
53 // https://manpages.debian.org/bullseye/manpages-dev/pivot_root.2.en.html#NOTES,
54 // I would end up with writeable rsync module mounts?!
55 if err := syscall.PivotRoot(newroot, putold); err != nil {
56 return fmt.Errorf("pivot_root(2): %v", err)
57 }
58
59 if err := os.Chdir("/"); err != nil {
60 return fmt.Errorf("chdir(/): %v", err)
61 }
62
63 // Only unmount the old root, but not delete it: we lack permission now that
64 // the root is re-mounted read-only.
65 putold = "/.pivot_root"
66 if err := syscall.Unmount(putold, syscall.MNT_DETACH); err != nil {
67 return fmt.Errorf("unmount(%s): %v", putold, err)
68 }
69
70 return nil
71 }
72
73 func namespace(osenv *rsyncos.Env, modules []rsyncd.Module, listen string) error {
74 if os.Getenv("GOKRAZY_RSYNC_NAMESPACE") != "" {
75 osenv.Logf("pid %d (inside Linux mount/pid namespace)", os.Getpid())
76
77 // Expected by the go-systemd package, and hard to set before creating
78 // the process in Go.
79 os.Setenv("LISTEN_PID", strconv.Itoa(os.Getpid()))
80
81 // Set mount point propagation to MS_SLAVE.
82 // See https://hechao.li/2020/06/09/Mini-Container-Series-Part-1-Filesystem-Isolation/
83 if err := syscall.Mount("", "/", "", syscall.MS_REC|syscall.MS_SLAVE, ""); err != nil {
84 return fmt.Errorf("mount(/, MS_SLAVE): %v", err)
85 }
86
87 // Create our own tmpfs mount so that we won’t end up with nodev,
88 // nosuid, noexec and/or atime, to prevent operation not permitted
89 // errors when remounting read-only():
90 // https://unix.stackexchange.com/questions/655409/in-a-user-namespace-as-non-root-on-a-nosuid-nodev-filesystem-why-does-a-bind-m
91 tmpdir, err := os.MkdirTemp("", "gokr-rsync")
92 if err != nil {
93 return err
94 }
95 if err := syscall.Mount("tmpfs", tmpdir, "tmpfs", syscall.MS_REC, ""); err != nil {
96 return fmt.Errorf("mount(tmpfs, %s): %v", tmpdir, err)
97 }
98
99 if err := os.Chdir(tmpdir); err != nil {
100 return err
101 }
102
103 // prepare read-only bind mounts for each configured rsync module:
104 osenv.Logf("mounting rsync modules read-only:")
105 for _, mod := range modules {
106 osenv.Logf(" rsync module %q from host=%s to namespace=/%s", mod.Name, mod.Path, mod.Name)
107 // TODO: restrict module names to not contain slashes. does rsync do that?
108 if err := os.MkdirAll(mod.Name, 0755); err != nil {
109 return err
110 }
111 if err := syscall.Mount(mod.Path, mod.Name, "none", syscall.MS_BIND|syscall.MS_RDONLY, ""); err != nil {
112 return err
113 }
114 }
115
116 wd, err := os.Getwd()
117 if err != nil {
118 return err
119 }
120
121 if err := pivotRoot(wd); err != nil {
122 return fmt.Errorf("pivotRoot(%q): %v", wd, err)
123 }
124
125 if err := dropPrivileges(osenv); err != nil {
126 return fmt.Errorf("dropPrivileges: %v", err)
127 }
128
129 for idx, mod := range modules {
130 mod.Path = "/" + mod.Name
131 modules[idx] = mod
132 }
133
134 if err := canUnexpectedlyWriteTo("."); err != nil {
135 return err
136 }
137
138 return nil
139 }
140
141 if os.Getuid() != 0 {
142 version(osenv)
143 osenv.Logf("environment: unprivileged")
144 return nil
145 }
146
147 version(osenv)
148 osenv.Logf("environment: privileged")
149 osenv.Logf("creating Linux mount/pid namespace for read-only rsync module mounts")
150
151 exe, err := os.Executable()
152 if err != nil {
153 return err
154 }
155
156 // Create the listener while still running as uid 0 and inherit it, so that
157 // we can listen on port 873 (rsync), which requires CAP_NET_BIND_SERVICE.
158 ln, err := net.Listen("tcp", listen)
159 if err != nil {
160 return err
161 }
162
163 cmd := exec.Command(exe, os.Args[1:]...)
164 cmd.Dir = "/"
165 // TODO: clean the environment
166 cmd.Env = append(os.Environ(),
167 "GOKRAZY_RSYNC_NAMESPACE=1",
168 "LISTEN_FDS=1", // ExtraFiles start at 3
169 "PATH=/bin:"+os.Getenv("PATH"))
170 cmd.Stdin = os.Stdin // for interactive debugging
171 cmd.Stdout = os.Stdout
172 cmd.Stderr = os.Stderr
173 lnFile, err := ln.(*net.TCPListener).File()
174 if err != nil {
175 return err
176 }
177 cmd.ExtraFiles = []*os.File{lnFile}
178 cmd.SysProcAttr = &syscall.SysProcAttr{
179 Cloneflags: unix.CLONE_NEWNS | unix.CLONE_NEWPID,
180 GidMappingsEnableSetgroups: false,
181 }
182 if err := cmd.Run(); err != nil {
183 return fmt.Errorf("%v: %v", cmd.Args, err)
184 }
185 return errIsParent
186 }
187
188 var errIsParent = errors.New("re-exec parent process sentinel error")