aboutsummaryrefslogtreecommitdiff
path: root/cmd/podman-mac-helper/install.go
blob: 7b8753820e51c1e7eb0ccfd421066819d1430fdd (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
//go:build darwin
// +build darwin

package main

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
	"syscall"
	"text/template"

	"github.com/spf13/cobra"
)

const (
	rwx_rx_rx = 0755
	rw_r_r    = 0644
)

const launchConfig = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Label</key>
	<string>com.github.containers.podman.helper-{{.User}}</string>
	<key>ProgramArguments</key>
	<array>
		<string>{{.Program}}</string>
		<string>service</string>
		<string>{{.Target}}</string>
	</array>
	<key>inetdCompatibility</key>
	<dict>
		<key>Wait</key>
		<false/>
	</dict>
	<key>UserName</key>
	<string>root</string>
	<key>Sockets</key>
	<dict>
		<key>Listeners</key>
		<dict>
			<key>SockFamily</key>
			<string>Unix</string>
			<key>SockPathName</key>
			<string>/private/var/run/podman-helper-{{.User}}.socket</string>
			<key>SockPathOwner</key>
			<integer>{{.UID}}</integer>
			<key>SockPathMode</key>
			<!-- SockPathMode takes base 10 (384 = 0600) -->
			<integer>384</integer>
			<key>SockType</key>
			<string>stream</string>
		</dict>
	</dict>
</dict>
</plist>
`

type launchParams struct {
	Program string
	User    string
	UID     string
	Target  string
}

var installCmd = &cobra.Command{
	Use:    "install",
	Short:  "installs the podman helper agent",
	Long:   "installs the podman helper agent, which manages the /var/run/docker.sock link",
	PreRun: silentUsage,
	RunE:   install,
}

func init() {
	addPrefixFlag(installCmd)
	rootCmd.AddCommand(installCmd)
}

func install(cmd *cobra.Command, args []string) error {
	userName, uid, homeDir, err := getUser()
	if err != nil {
		return err
	}

	labelName := fmt.Sprintf("com.github.containers.podman.helper-%s.plist", userName)
	fileName := filepath.Join("/Library", "LaunchDaemons", labelName)

	if _, err := os.Stat(fileName); err == nil || !os.IsNotExist(err) {
		return errors.New("helper is already installed, uninstall first")
	}

	prog, err := installExecutable(userName)
	if err != nil {
		return err
	}

	target := filepath.Join(homeDir, ".local", "share", "containers", "podman", "machine", "podman.sock")
	var buf bytes.Buffer
	t := template.Must(template.New("launchdConfig").Parse(launchConfig))
	err = t.Execute(&buf, launchParams{prog, userName, uid, target})
	if err != nil {
		return err
	}

	file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, rw_r_r)
	if err != nil {
		return fmt.Errorf("creating helper plist file: %w", err)
	}
	defer file.Close()
	_, err = buf.WriteTo(file)
	if err != nil {
		return err
	}

	if err = runDetectErr("launchctl", "load", fileName); err != nil {
		return fmt.Errorf("launchctl failed loading service: %w", err)
	}

	return nil
}

func restrictRecursive(targetDir string, until string) error {
	for targetDir != until && len(targetDir) > 1 {
		info, err := os.Lstat(targetDir)
		if err != nil {
			return err
		}
		if info.Mode()&fs.ModeSymlink != 0 {
			return fmt.Errorf("symlinks not allowed in helper paths (remove them and rerun): %s", targetDir)
		}
		if err = os.Chown(targetDir, 0, 0); err != nil {
			return fmt.Errorf("could not update ownership of helper path: %w", err)
		}
		if err = os.Chmod(targetDir, rwx_rx_rx|fs.ModeSticky); err != nil {
			return fmt.Errorf("could not update permissions of helper path: %w", err)
		}
		targetDir = filepath.Dir(targetDir)
	}

	return nil
}

func verifyRootDeep(path string) error {
	path = filepath.Clean(path)
	current := "/"
	segs := strings.Split(path, "/")
	depth := 0
	for i := 1; i < len(segs); i++ {
		seg := segs[i]
		current = filepath.Join(current, seg)
		info, err := os.Lstat(current)
		if err != nil {
			return err
		}

		stat := info.Sys().(*syscall.Stat_t)
		if stat.Uid != 0 {
			return fmt.Errorf("installation target path must be solely owned by root: %s is not", current)
		}

		if info.Mode()&fs.ModeSymlink != 0 {
			target, err := os.Readlink(current)
			if err != nil {
				return err
			}

			targetParts := strings.Split(target, "/")
			segs = append(targetParts, segs[i+1:]...)

			if depth++; depth > 1000 {
				return errors.New("reached max recursion depth, link structure is cyclical or too complex")
			}

			if !filepath.IsAbs(target) {
				current = filepath.Dir(current)
				i = -1 // Start at 0
			} else {
				current = "/"
				i = 0 // Skip empty first segment
			}
		}
	}

	return nil
}

func installExecutable(user string) (string, error) {
	// Since the installed executable runs as root, as a precaution verify root ownership of
	// the entire installation path, and utilize sticky + read only perms for the helper path
	// suffix. The goal is to help users harden against privilege escalation from loose
	// filesystem permissions.
	//
	// Since userspace package management tools, such as brew, delegate management of system
	// paths to standard unix users, the daemon executable is copied into a separate more
	// restricted area of the filesystem.
	if err := verifyRootDeep(installPrefix); err != nil {
		return "", err
	}

	targetDir := filepath.Join(installPrefix, "podman", "helper", user)
	if err := os.MkdirAll(targetDir, rwx_rx_rx); err != nil {
		return "", fmt.Errorf("could not create helper directory structure: %w", err)
	}

	// Correct any incorrect perms on previously existing directories and verify no symlinks
	if err := restrictRecursive(targetDir, installPrefix); err != nil {
		return "", err
	}

	exec, err := os.Executable()
	if err != nil {
		return "", err
	}
	install := filepath.Join(targetDir, filepath.Base(exec))

	return install, copyFile(install, exec, rwx_rx_rx)
}

func copyFile(dest string, source string, perms fs.FileMode) error {
	in, err := os.Open(source)
	if err != nil {
		return err
	}

	defer in.Close()
	out, err := os.OpenFile(dest, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, perms)
	if err != nil {
		return err
	}

	defer out.Close()
	if _, err := io.Copy(out, in); err != nil {
		return err
	}

	return nil
}